【问题标题】:Get decltype of function获取函数的decltype
【发布时间】:2015-10-01 12:46:46
【问题描述】:

我想获取函数的类型并创建一个std::vector。例如,我有

int foo(int a[], int n) { return 1; }
int bar(int a[], int n) { return 2; }

这样的函数向量将是:

std::vector< std::function<int(int[],int)> > v;

一般来说,decltype() 会更好,例如:

std::vector< decltype(foo) > v;

但是,这会导致编译错误。

我猜原因是decltype()无法区分

int (*func)(int[], int)
std::function<int(int[], int)>

有没有办法解决这个问题?

【问题讨论】:

    标签: c++ decltype


    【解决方案1】:

    使用任一:

    std::vector< decltype(&foo) > v;
    

    或:

    std::vector< decltype(foo)* > v;
    

    或:

    std::vector< std::function<decltype(foo)> > v;
    

    但是,一旦foo 过载,上述所有解决方案都会失败。另请注意,std::function 是一种类型擦除器,其代价是虚拟调用。

    中,您可以让std::vector 从初始化列表中推导出类模板参数:

    std::vector v{ foo, bar };
    

    【讨论】:

    • 只有第三个 (std::function) 选项应该适用于不同的功能,例如 foo vs bar
    【解决方案2】:

    通过Piotr Skotnicki扩展answer

    decltype(foo)
    

    具有的类型

    int(int[], int)
    

    这不是函数指针。为了获得函数指针,您要么必须使用地址为foo decltype(&amp;foo)decltype,要么可以在类型末尾添加* 以声明指向foo 类型的指针decltype(foo)*

    【讨论】:

      【解决方案3】:

      解决办法是这样的:

      typedef std::function<int(int[], int)> sf;
      std::vector< sf > v2;
      

      没关系

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多