当我不知道函数的签名时,有什么方法可以在编译时检测给定类型是否是 C++03 中的函数类型?如果是,怎么办?
(我只需要这个用于自由函数,而不是成员函数。)
最佳答案
感谢 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> { };
关于c++ - 检测给定类型是否为 C++03 中的函数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25275015/