获取函数的decltype

21

我想获取函数的类型并创建一个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)>

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

3个回答

28

请选择以下任意一种:

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 和 bar 吗? - Tobi Akinyemi

21

根据Piotr Skotnicki回答进行详细说明:

decltype(foo)

物品的类型是否已经确定?

int(int[], int)

哪个不是函数指针。 要获取函数指针,您可以使用decltypefoo的地址decltype(&foo)或者在类型末尾添加*以声明指向foo类型的指针decltype(foo)*


3
解决方案如下:

解决方法如下:

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

而且这很好


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接