Get decltype of function

末鹿安然 提交于 2020-07-28 13:03:27

问题


I want to get the type of a function and create a std::vector of it. For example, I have

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

and a vector of functions like this would be:

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

And in general, a decltype() would be better, like:

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

however, this will result in a compilation error.

I guess the reason is that decltype() cannot distinguish between

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

Is there a way to fix this?


回答1:


Use either:

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

or:

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

or:

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

However, all of the above solutions will fail once foo is overloaded. Also note that std::function is a type-eraser which comes at the cost of a virtual call.

In c++17, you can let std::vector deduce class template arguments from the initializer list:

std::vector v{ foo, bar };



回答2:


To expand on the answer by Piotr Skotnicki

decltype(foo)

Has the type of

int(int[], int)

Which is not a function pointer. In order to get a function pointer you either have to use decltype with the address of foo decltype(&foo) or you can add a * to the end of the type to declare a pointer to the type of foo decltype(foo)*




回答3:


The solution is like this :

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

and it is ok



来源:https://stackoverflow.com/questions/32887979/get-decltype-of-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!