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?
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 };
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)*
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With