I'd like an std::array
of function pointers. The only similar examples I can find are old-style raw arrays, or std::array
of std::function
.
Is it possible to translate this syntax:
bool (*arr[2])(int) = { foo, foo2 };
declaring an array of 2 functions, taking an int argument and returning a bool
...
..to use a std::array
?
By the “clockwise/spiral rule”, bool (*)(int)
is a pointer to a function that takes int
and returns bool
, so:
std::array<bool (*)(int), 2> arr = { /* ... */ };
or with a type alias:
using FunPtr = bool (*)(int);
std::array<FunPtr, 2> arr = { /* ... */ };
With c++17
and std::array
you do not even need to care to much about the type
#include <iostream>
#include <array>
int foo(int f)
{
return f*f;
}
int bar(int b)
{
return b*b*b;
}
int main()
{
std::array arr = {&foo, &bar};
std::cout << arr[0](6);
std::cout << arr[1](3);
return 0;
}
https://godbolt.org/z/7qnY4s781
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