简体   繁体   English

如何在C++中创建一个匿名函数数组?

[英]How to create an array of anonymous functions in C++?

C++ has 'lambdas' or anonymous functions. C++ 具有“lambdas”或匿名函数。 If they do not capture, they can be used in the place of function pointers.如果不捕获,可以用它们代替 function 指针。 I could also declare an array of function pointers as follows:我还可以声明一个 function 指针数组,如下所示:

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:但是我想不出在全局数组初始值设定项中使用 C++ lamdas 代替 function 名称的正确语法:

#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++?在 C++ 中初始化匿名函数指针数组的正确方法是什么?

The code is OK.代码没问题。 Upgrade your compiler.升级你的编译器。

The result of running g++ --version :运行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 :使用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.问题是由于在 C++11 中添加对 lambda 表达式的支持之前,编译器默认使用旧版本 C++。

All I had to do was to tell the compiler to use C++11 (or newer):我所要做的就是告诉编译器使用 C++11(或更新版本):

g++ /Users/user/Lambda.cpp --std=c++11

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM