【发布时间】:2014-12-09 13:34:13
【问题描述】:
目前,我是using this method to check if a class has a method with a specific signature.
参加Walter E. Brown's metaprogramming CppCon2014 talk 之后,我开始想知道void_t 是否可以在这种特殊情况下使用,以使代码更清晰和更具可读性。
但是,我在思考 void_t 时遇到了麻烦 - 到目前为止,我知道 void_t 可以帮助我在编译时确定表达式是否有效。
例子:
template< class, class = void >
struct has_type_data_member : false_type { };
template< class T >
struct has_type_data_member<T, void_t<decltype(T::data)>> : true_type { };
如果decltype(T::type) 是一个有效的表达式,has_type_data_member<T> 将是一个真正的编译时常量。因此,我们确定T 有一个名为data 的成员字段。
我想使用相同的方法来检查类型 T 是否具有具有特定名称和特定签名的方法。
假设我想检查T 是否有一个名为getCount() 的方法返回int。这就是我期望的工作((Ideone.com link)):
template< class, class = void >
struct hasGetCount : false_type { };
template< class T >
struct hasGetCount<T, VoidT<decltype(T::getCount)>>
: std::is_same<decltype(std::declval<T>().getCount()), int>::type { };
很遗憾,static_assert 测试没有通过。
我做错了什么?在这种情况下可以使用void_t吗?
额外问题:
- 如何检查方法签名是否与用户在原始实现中传递的签名相同?
-
我可以使用宏来定义这样的辅助结构:
DEFINE_METHOD_CHECKER(hasGetCount, getCount); // ... static_assert(hasGetCount<ClassWithGetCount>::value == true, "");是否可以避免必须先定义
struct然后检查结构的值?我的意思是,是否可以使用宏来编写这样的东西?示例:static_assert(CHECK_METHOD(ClassWithGetCount, getCount)::value == true, "");
【问题讨论】:
-
命名非静态成员函数的 id-expression 不能用于
decltype。 -
@T.C.:我明白了 - 是否有另一种方法可以根据类型是否有/没有方法来生成有效/无效表达式?
标签: c++ templates void template-meta-programming c++14