Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get decltype of function

Tags:

c++

decltype

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?

like image 880
Q. Wang Avatar asked Oct 01 '15 12:10

Q. Wang


2 Answers

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 };
like image 167
Piotr Skotnicki Avatar answered Sep 19 '22 11:09

Piotr Skotnicki


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

like image 25
NathanOliver Avatar answered Sep 20 '22 11:09

NathanOliver