Search code examples
c++decltype

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?


Solution

  • 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 };