std::is_function 的实施 - 为什么我的实施行为不同?

Implementation of std::is_function - why my implementation behaves differently?

我有以下 is_function 的实现:

template <typename SomeType>
struct _is_function_helper : public _false_expression {};
template <typename ReturnType, typename ... ArgumentTypes>
struct _is_function_helper<ReturnType (ArgumentTypes ...)> : _true_expression {};
template <typename ReturnType, typename ... ArgumentTypes>
struct _is_function_helper<ReturnType (ArgumentTypes ..., ...)> : _true_expression {};

template <typename SomeType>
struct _is_function : public _boolean_expression<_is_function_helper<typename _remove_cv<typename _remove_reference<SomeType>::Type>::Type>::value> {};

我删除了引用、cv 限定符,然后尝试从与 _is_function_helper 相同的 bool 表达式继承。然后我尝试了以下测试:

void func(int,int) { };

struct A { void foo(int); };

....

auto r = func;
std::cout << std::boolalpha;
std::cout << std::is_function<decltype(func)>::value << " " << _is_function<decltype(func)>::value << std::endl;
std::cout << std::is_function<int(int)>::value << " " << _is_function<int(int)>::value << std::endl;
std::cout << std::is_function<int(*)(int)>::value << " " << _is_function<int(*)(int)>::value << std::endl;
std::cout << std::is_function<decltype(r)>::value << " " << _is_function<decltype(r)>::value << std::endl;
std::cout << std::is_function<decltype(*r)>::value << " " << _is_function<decltype(*r)>::value << std::endl;
std::cout << std::is_function<decltype(&A::foo)>::value << " " << _is_function<decltype(&A::foo)>::value << std::endl;

这里是这些测试的输出:

true true
true true
false false
false false
false true
false false

我有两个问题:

  1. 为什么第 5 个测试用例的输出不同?
  2. 如何使用 _is_function 检测结构的成员函数?

第 5 种情况的输出不同,因为 decltype(*r) 是对函数的引用。您的实施删除了此引用,但 std::is_function 没有。

您可以通过添加这样的特化来检测成员函数指针:

template <typename ReturnType, typename ... ArgumentTypes, typename T>
struct _is_function_helper<ReturnType (T::*) (ArgumentTypes ...)> 
    : _true_expression {};