`std :: enable_if`是函数指针 - 怎么样? [英] `std::enable_if` is function pointer - how?
问题描述
如果用户将函数指针作为参数传递,我想使用SFINAE来启用特定模板。
I want to use SFINAE to enable a particular template if the user passes a function pointer as a parameter.
我已经google了,但是没有发现任何东西 - 我也试过看看< type_traits>
t找到类似于 is_function_ptr< T>
的任何东西。
I have googled around but found nothing - I also tried looking at the <type_traits>
documentation but couldn't find anything that resembled a is_function_ptr<T>
.
通过函数指针, TReturn(*)(TArgs ...)
。
推荐答案
是一个类型trait,确定某事是否是一个函数指针和几个测试用例。注意,要测试某个函数是否是一个函数指针,需要测试 std :: is_pointer< P> :: value
是 true
,如果
为 std :: is_function< T> :: value
是 true
c> T P
,并删除指针。下面的代码只是这样做:
Below is a type trait determining if something is a function pointer and a couple of test cases. Note, that to test if something is a function pointer, you need to test if std::is_pointer<P>::value
is true
and if std::is_function<T>::value
is true
where T
is P
with the pointer removed. The code below just does that:
#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){});
}
这篇关于`std :: enable_if`是函数指针 - 怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!