2

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?

8
  • Cannot reproduce your problem. Compiles fine for me, on gcc 12, and I get the expected result, -2. Commented Sep 29, 2022 at 19:57
  • 4
    The code is OK. Upgrade your compiler. Commented Sep 29, 2022 at 19:59
  • it's interesting, though, that you invoke g++ and it seems to call clang. Commented Sep 29, 2022 at 20:05
  • @n.1.8e9-where's-my-sharem. I notice MSVC and gcc like it but clang does not. Commented Sep 29, 2022 at 20:05
  • 2
    Apple Clang also defaults to C++98 if I am not mistaken (as only of the current major compilers as far as I am aware), which is probably why the compiler is complaining about the lambda syntax in general. (Lambdas were introduced with C++11.) Commented Sep 29, 2022 at 20:20

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.