c++ - C++编译时检查模板类型中是否存在方法
问题描述
我有一个调用成员函数的模板。如何检查static_assert
该方法是否存在?
struct A {
};
struct B {
int foo() { return 42; } };
template <typename T> struct D {
static_assert(/* T has foo */, "T needs foo for reasons");
int bar() {
return t.foo();
}
T t; };
int main() {
D<A> d;
std::cout << d.bar() << std::endl;
return 0; }
我知道这只会生成 A 没有 foo 的编译器错误,但我想检查并使用static_assert
.
解决方案
由于您使用static_assert
我断言您至少使用 C++11。这允许编写如下内容:
#include <type_traits>
template<class ...Ts>
struct voider{
using type = void;
};
template<class T, class = void>
struct has_foo : std::false_type{};
template<class T>
struct has_foo<T, typename voider<decltype(std::declval<T>().foo())>::type> : std::true_type{};
你只需使用静态字段value
( has_foo<your_type>::value
) - 如果它是真的,那么你的类型有 function foo
。
推荐阅读
- python - 尝试分组,然后根据多个值对数据框进行排序
- vaadin - Vaadin 自动更新 package-lock.json 中的版本
- javascript - 加载 gRPC 二进制模块失败,因为它没有为当前系统安装
- java - 原因在哪里:连接到 Glassfish 服务器时出错?
- php - 使用 PDO 和 DBLIB 驱动程序查询具有链接服务器的 SQL Server 数据库
- javascript - React memoized 组件重新渲染,无需更改 props
- node.js - 使用 NodeJS 开发 lambda 时,aws-sdk 可以成为开发依赖项吗?
- javascript - 具有动态项目槽的 vuetify 数据表格式列
- html - Bootstrap 3 - 为响应式表格自定义列宽
- java - 调试器无法附加