之前的文章里……比较那啥,
总之这个版本可以分别 判断字段/成员函数/静态函数/typedef
主要用了c++11的decltype和一些萃取类,这次就没办法用变通的方式放到低版本去了
注意,对于成员函数或静态函数,如果有重载比如 a() a(int) 反而会得到0的结果
后面提供了一种验证语法可行性的方法,可以解决重载问题
#include "stdafx.h" #include <xtr1common> #include <string> template<typename T, typename C = std::enable_if <std::is_member_object_pointer<decltype(&T::first)>::value >::type> short existFirst() {} template<typename T> char existFirst(...) {} template<typename T, typename C = std::enable_if <std::is_member_function_pointer<decltype(&T::c_str)>::value >::type> short exist_c_str() {} template<typename T> char exist_c_str(...) {} template<typename T, typename C = std::enable_if <std::is_function<std::remove_pointer_t<decltype(&T::staticfun)>>::value >::type> short exist_staticfun() { return 0; } template<typename T> char exist_staticfun(...) {} template<typename T, typename C = std::enable_if <std::is_pointer<T::first_type*>::value >::type> short exist_first_type() {} template<typename T> char exist_first_type(...) {} template<typename T, typename C = std::enable_if <std::is_integral<decltype(((T*)0)->first(), 1)>::value>::type> short exist_member_fun_overload() { } template<typename T> char exist_member_fun_overload(...) { } struct A { static void staticfun(); // void first(); void first(); }; struct B { void staticfun(); void first_type(); static void c_str(); void first(int); }; int _tmain(int argc, _TCHAR* argv[]) { printf("%d\n", sizeof(existFirst<std::pair<int, int>>()) - 1); //1 printf("%d\n", sizeof(existFirst<std::string>()) - 1); //0 printf("%d\n", sizeof(existFirst<int>()) - 1); //0 printf("%d\n", sizeof(existFirst<A>()) - 1); //0 puts(""); printf("%d\n", sizeof(exist_c_str<std::pair<int, int>>()) - 1); //0 printf("%d\n", sizeof(exist_c_str<std::string>()) - 1); //1 printf("%d\n", sizeof(exist_c_str<int>()) - 1); //0 printf("%d\n", sizeof(exist_c_str<B>()) - 1); //0 puts(""); printf("%d\n", sizeof(exist_first_type<std::pair<int, int>>()) - 1);//1 printf("%d\n", sizeof(exist_first_type<std::string>()) - 1); //0 printf("%d\n", sizeof(exist_first_type<int>()) - 1); //0 printf("%d\n", sizeof(exist_first_type<B>()) - 1); //0 puts(""); printf("%d\n", sizeof(exist_staticfun<B>()) - 1); //0 printf("%d\n", sizeof(exist_staticfun<A>()) - 1); //1 printf("%d\n", sizeof(exist_staticfun<std::string>()) - 1); //0 printf("%d\n", sizeof(exist_staticfun<int>()) - 1); //0 puts(""); printf("%d\n", sizeof(exist_member_fun_overload<A>()) - 1); //1 printf("%d\n", sizeof(exist_member_fun_overload<B>()) - 1); //0 return 0; }