C++ has 'lambdas' or anonymous functions. If they do not capture, they can be used in the place of function pointers. I could also declare an array of function pointers as follows:
double (*const Trig[])(double) = {sin, cos, tan};
cout << Trig[0](M_PI/2) << endl; // Prints 1
However I cannot figure out the correct syntax to use C++ lamdas in the place of function names in a global array initializer:
#include <iostream>
using namespace std;
static int (*const Func[])(int, int) = {
[](int x, int y) -> int {
// ^ error: expected expression
return x+y;
},
[](int x, int y) -> int {
return x-y;
},
[](int x, int y) -> int {
return x*y;
},
[](int x, int y) -> int {
return x/y;
}
};
int main(void) {
cout << Func[1](4, 6) << endl;
}
What is the correct way to initialize an array of pointers to anonymous functions in C++?
The code is OK. Upgrade your compiler.
The result of running g++ --version
:
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.0 (clang-1200.0.32.29)
Target: x86_64-apple-darwin19.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
Compiler error from using g++ /Users/user/Lambda.cpp
:
/Users/user/Lambda.cpp:4:3: error: expected expression
[](int x, int y) -> int {
^
1 error generated.
How can I configure my compiler to accept this code?
The code is correct. The problem was due to the compiler defaulting to an older version of C++, before support for lambda expressions was added in C++11.
All I had to do was to tell the compiler to use C++11 (or newer):
g++ /Users/user/Lambda.cpp --std=c++11