【问题标题】:How to determine if an argument is a pure function pointer?如何确定参数是否是纯函数指针?
【发布时间】:2012-11-27 03:33:47
【问题描述】:

我想写一个名为is_pure_func_ptr的trait-checker,它可以判断类型是否为纯函数指针,如下:

#include <iostream>

using namespace std;

void f1()
{};

int f2(int)
{};

int f3(int, int)
{};

struct Functor
{
    void operator ()()
    {}
};

int main()
{
    cout << is_pure_func_ptr<decltype(f1)>::value << endl; // output true
    cout << is_pure_func_ptr<decltype(f2)>::value << endl; // output true
    cout << is_pure_func_ptr<decltype(f3)>::value << endl; // output true
    cout << is_pure_func_ptr<Functor>::value << endl;      // output false
    cout << is_pure_func_ptr<char*>::value << endl;        // output false
}

我的问题是:如何实现?

【问题讨论】:

  • “纯”到底是什么意思?对于纯粹的一些定义,Functor 对我来说看起来很纯粹。
  • @Mat,我的例子是为了定义什么是“纯函数指针”。
  • 问题是,pure functions 是一个成熟的术语。所以你的问题有点混乱。如果这就是您的意思,也许可以替换为“普通/顶级函数,而不是成员函数、lambda 或其他可调用对象”?
  • 是的,你的意见是正确的。

标签: c++ function function-pointers functor typetraits


【解决方案1】:

正如 Joachim Pileborg 所说,std::is_function 将完成这项工作。 如果这不是您的选择,但您确实有 C++11 支持(意味着您只想知道如何自己实现它,或者您的标准库还不存在),您可以执行以下操作:

template<typename T>
struct is_pure_func_ptr: public std::false_type {};
template<typename Ret, typename... Args>
struct is_pure_func_ptr<Ret(Args...)>: public std::true_type {};//detecting functions themselves
template<typename Ret, typename... Args>
struct is_pure_func_ptr<Ret(*)(Args...)>: public std::true_type {};//detecting function pointers

This works,但在支持具有不同调用约定和/或 cv 限定指针的函数时,您可能需要额外的工作

【讨论】:

  • 非常感谢。灰熊。您的解决方案简洁美观!
【解决方案2】:

如果你有 C++11 标准库,试试std::is_function

【讨论】:

  • OP 希望它为仿函数返回 false
  • 是的。我想区分纯函数指针和函子。
  • @KarthikT 正如 OPs 示例中所使用的那样,确实如此。
  • 哦,抱歉.. 一定是困了,错过了描述,+1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-15
  • 2018-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多