SFINAE检测静态方法
SFINAE to detect static method
我正在尝试实现一种机制来检测提供的类是否包含一些静态方法。这是非常简单的代码,但我不明白为什么decltype()
不能按预期工作EnableIfHasFooMethod
类的专业化:
#include <iostream>
struct A {
static int Foo() { return 0; }
};
template <class T, class = void>
struct EnableIfHasFooMethod {};
template <class T>
struct EnableIfHasFooMethod<T, decltype(T::Foo)> {
typedef void type;
};
template <class T, class = void>
struct HasFooMethod {
static const bool value = false;
};
template <class T>
struct HasFooMethod<T, typename EnableIfHasFooMethod<T>::type> {
static const bool value = true;
};
int main() {
std::cout << HasFooMethod<A>::value << std::endl;
return 0;
}
输出是0
,但应该1
。
你忘了添加void()
template <class T>
struct EnableIfHasFooMethod<T, decltype(T::Foo, void())> { /* ... */ };
// ...........................................^^^^^^^^
您需要匹配中的第二种类型(void
// ........................vvvv
template <class T, class = void>
struct EnableIfHasFooMethod {};
因此,您的decltype()
必须返回 void
IFF(当且仅当)T
中有Foo()
成员。
你不能写
decltype( T::Foo )
因为,在这种情况下,decltype()
返回无法void
的成员类型Foo
(如果存在)。
你不能写
decltype( void() )
因为,在这种情况下,decltype()
返回void
,但您希望它,如果有一个Foo
成员在T
所以解决方案是
decltype( T::Foo , void() )
所以SFINAE可以工作,如果没有Foo
成员,则替换失败,如果有Foo
,则返回void
。
由于人们可能仍然对此感兴趣,因此让我指出EnableIfHasFooMethod
是多余的(如果我没记错的话)。这也应该同样有效:
template <class T, class = void>
struct HasFooMethod: public std::false_type {};
template <class T>
struct HasFooMethod<T, std::void_t<decltype(T::Foo)>>: public std::true_type {};
相关文章:
- 用于C++的静态二进制检测或二进制重写工具和框架
- 尝试了解在导入的静态方法上使用删除方法时的错误
- 如何通过命名空间调用非静态方法
- 如何在没有实例的情况下获取非静态方法的类型?
- 调用从模板派生的类的静态方法,而不指定模板
- 如何在 c++ 中异步调用静态方法?
- C++ 将静态方法转换为简单方法
- 从另一个标头中的标头调用静态方法
- C++中静态方法的局部变量范围
- 如何启用使用另一个类的静态方法的模板函数的自动推导,从而消除冗长的调用方代码
- 使用本机 JNI 静态方法实现C++ Java 运行时错误
- 当只有静态方法受到影响时,如何解决C++中的链接器错误?
- 静态变量在同一个翻译单元中被静态方法使用时是否保证被初始化?
- 为什么链接器报告全局函数的乘法定义符号,而不是类静态方法
- 从部分专用模板方法调用模板非静态方法
- 如何使用 c++ 在 cocos2dx 中定义非静态方法
- 使用 CMake 的静态方法链接错误
- 在子类上调用模板化静态方法时获取类的类型名
- 仅具有公共静态方法的帮助程序类
- SFINAE检测静态方法