Q. Wang
Q. Wang

Reputation: 233

Get decltype of function

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?

Upvotes: 23

Views: 13614

Answers (3)

Piotr Skotnicki
Piotr Skotnicki

Reputation: 48457

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 , you can let std::vector deduce class template arguments from the initializer list:

std::vector v{ foo, bar };

Upvotes: 29

Stathis Andronikos
Stathis Andronikos

Reputation: 1259

The solution is like this :

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

and it is ok

Upvotes: 3

NathanOliver
NathanOliver

Reputation: 180630

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)*

Upvotes: 22

Related Questions