c++ - `std::enable_if` 是函数指针——怎么样?

标签 c++ templates pointers c++11 enable-if

如果用户将函数指针 作为参数传递,我想使用 SFINAE 启用特定模板。

我用谷歌搜索但一无所获 - 我也尝试查看 <type_traits>文档,但找不到任何类似于 is_function_ptr<T> 的内容.

函数指针,我指的是全局函数指针,比如TReturn(*)(TArgs...) .

最佳答案

下面是确定某物是否为函数指针的类型特征和几个测试用例。请注意,要测试某物是否是函数指针,您需要测试是否 std::is_pointer<P>::valuetrue如果std::is_function<T>::valuetrue其中 TP删除指针。下面的代码就是这样做的:

#include <type_traits>
#include <iostream>
#include <utility>

template <typename Fun>
struct is_fun_ptr
    : std::integral_constant<bool, std::is_pointer<Fun>::value
                            && std::is_function<
                                   typename std::remove_pointer<Fun>::type
                               >::value>
{
};

template <typename Fun>
typename std::enable_if<is_fun_ptr<Fun>::value>::type
test(Fun) {
    std::cout << "is a function pointer\n";
}

template <typename Fun>
typename std::enable_if<!is_fun_ptr<Fun>::value>::type
test(Fun) {
    std::cout << "is not a function pointer\n";
}

void f0() {}
void f1(int) {}
void f2(int, double) {}

struct s0 { void operator()() {} };
struct s1 { void operator()(int) {} };
struct s2 { void operator()(int, double) {} };

int main()
{
    int v0(0);
    int* p0(&v0);
    void (*p1)() = &f0;
    void (**p2)() = &p1;
    std::cout << "v0="; test(v0);
    std::cout << "p0="; test(p0);
    std::cout << "p1="; test(p1);
    std::cout << "p2="; test(p2);

    std::cout << "f0="; test(&f0);
    std::cout << "f1="; test(&f1);
    std::cout << "f2="; test(&f2);

    std::cout << "s0="; test(s0());
    std::cout << "s1="; test(s1());
    std::cout << "s2="; test(s2());

    std::cout << "l0="; test([](){});
    std::cout << "l1="; test([](int){});
    std::cout << "l2="; test([](int, double){});
}

关于c++ - `std::enable_if` 是函数指针——怎么样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18666218/

相关文章:

c++ - 将无符号字符按位左移 16 是什么意思

c++ - 使用模板的选择排序函数没有匹配的函数调用(C++)

c++ - 在具有指针参数的模板实例化之间进行选择

c++ - 从 HGDIOBJ 到 HBRUSH 的转换

c++ - 访问双指针导致段错误

c - 这个例子中的 char** 和 char* 有什么区别?

c++ - 数组上的指针运算

c - 用于交换字符串的输出相关查询

c++ - 在不同的类中使用单例

c++ - 给定传递给它的参数类型,如何确定函数参数的类型?