gpt4 book ai didi

c++ - std::is_function 的实现 - 为什么我的实现表现不同?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:28:31 26 4
gpt4 key购买 nike

我有以下 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 {};

关于c++ - std::is_function 的实现 - 为什么我的实现表现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36200117/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com