Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 608
rare77 Avatar asked Sep 18 '25 20:09

rare77


2 Answers

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 = { /* ... */ };
like image 105
Evg Avatar answered Sep 21 '25 10:09

Evg


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

like image 40
Logman Avatar answered Sep 21 '25 10:09

Logman