#include <iostream> struct Hello { int helloworld() { return 0; } }; struct Generic {}; // SFINAE test template <typename T> class has_helloworld { typedef char yes[1]; typedef yes no[2]; template <typename C> static yes& test( typeof(&C::helloworld) ); template <typename C> static no& test(...); public: enum { value = sizeof(test<T>(0)) == sizeof(yes) }; }; int main(int argc, char *argv[]) { std::cout << has_helloworld<Hello>::value << std::endl; std::cout << has_helloworld<Generic>::value << std::endl; return 0; }
参考资料
Is it possible to write a C++ template to check for a function's existence?
SFINAE to check for inherited member functions
Substitution failure is not an error(SFINAE)
An introduction to C++'s SFINAE concept: compile-time introspection of a class member