当我不知道函数的签名时,有没有办法在编译时检测给定类型是否是C ++ 03中的函数类型?如果是这样,怎么样?
(我只需要这个免费功能,而不是成员功能。)
答案 0 :(得分:3)
我自己找到了一个解决方案,感谢Kerrek SB的初步提示:
template<class T> struct is_function
{
private:
static T &declval;
static char (&test(T *))[2];
template<class U>
static char (&test(U const &))[1];
public:
static bool const value = sizeof(test(declval)) > 1;
};
template<> struct is_function<void> { static bool const value = false; };
template<class T> struct is_function<T const> : is_function<T> { };
template<class T> struct is_function<T volatile> : is_function<T> { };
template<class T> struct is_function<T const volatile> : is_function<T> { };
template<class T> struct is_function<T &> { static bool const value = false; };
结果成员函数指针也很容易:
template<class> struct is_member_function_pointer { static bool const value = false; };
template<class T> struct is_member_function_pointer<T const> : is_member_function_pointer<T> { };
template<class T> struct is_member_function_pointer<T volatile> : is_member_function_pointer<T> { };
template<class T> struct is_member_function_pointer<T const volatile> : is_member_function_pointer<T> { };
template<class T, class U> struct is_member_function_pointer<T U::*> : is_function<T> { };