c++ - 检测给定类型是否为 C++03 中的函数类型

标签 c++ templates template-meta-programming c++03

当我不知道函数的签名时,有什么方法可以在编译时检测给定类型是否是 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/

相关文章:

c++ - 使用模板元编程检测函数可以采用的最大参数数量

c++ - 继承时删除重复的模板类型名条目

c++ - Tesseract OCR 德语特殊字符

c++ - Qt 使用 Ui 文件和 QUiLoader

c++ - 使用 g++ 删除了 linux 中的 std basic_stringstream 函数

c++ - 显式链接到 DLL 中的类

c++ - 模板化构造函数与模板化复制构造函数

c++ - 模板类编译 "expected constructor, destructor, or type conversion before ‘<’ token”错误

azure - 从 Azure Keyvault 部署 Web 应用程序证书并创建 SSL 绑定(bind)

c++ - std::条件与 SFINAE