Search code examples
c++function-pointers

C++ std array of function pointer syntax


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?


Solution

  • 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 = { /* ... */ };