我想知道如何将指向非静态成员函数的指针传递到模板中? 这是简化的代码:
template<typename, typename>
struct contains;
template<typename T, typename R, typename... Ts>
struct contains<T, R(Ts...)>
{
static constexpr bool result = std::disjunction_v<std::is_same<T, Ts>...>;
};
class A
{
public:
static void staticFoo(int a, double* b) {}
void foo(int a, double* b) {}
};
void foo(int a, double* b) {}
int main ()
{
//ok, this works
std::cout << std::boolalpha << contains<double*, decltype(foo)>::result;
//this too
std::cout << std::boolalpha << contains<double*, std::remove_pointer_t<decltype(&A::staticFoo)>>::result;
//boom, error
std::cout << std::boolalpha << contains<double*, decltype(&A::foo)>::result;
return 0;
}
执行此代码,出现错误:
incomplete type 'contains<double*, void (A::*)(int, double*)>' used in nested name specifier
据我了解,类型为:
void(int, double*)
void(*)(int, double*)
void(A::*)(int, double*)
在第二种情况下,我可以使用std::remove_pointer_t
,但是在第三种情况下,如何从函数签名中删除(A::*)
?
答案 0 :(得分:2)
您可以添加其他专长:
template<typename, typename> struct contains;
template<typename T, typename R, typename... Ts>
struct contains<T, R(Ts...)>
{
static constexpr bool result = std::disjunction_v<std::is_same<T, Ts>...>;
};
template<typename T, typename R, typename... Ts>
struct contains<T, R (*)(Ts...)> : contains<T, R(Ts...)>
{
};
template<typename T, typename C, typename R, typename... Ts>
struct contains<T, R (C::*)(Ts...)> : contains<T, R(Ts...)>
{
};
// And even more for R (C::*) (Ts... ...) const volatile &&
然后
int main ()
{
std::cout << std::boolalpha << contains<double*, decltype(foo)>::result;
std::cout << std::boolalpha << contains<double*, decltype(&A::staticFoo)>::result;
std::cout << std::boolalpha << contains<double*, decltype(&A::foo)>::result;
}