c++ - lambda 函数的静态数组 (C++)

标签 c++ c++11 lambda

我想做这样的事情(在类里面):

static constexpr MyStruct ops[6] = {
    {'+', [&] (double a, double b) { return a+b; } },
    {'-', [&] (double a, double b) { return a-b; } },
    ...
};

其中 MyStruct 定义为:

typedef double (*binOp)(double, double);
struct MyStruct {
    char c;
    binOp fn;
};

我也试过:

std::function <double(double,double)> fn;

对于 fn 的定义,但运气不好。

我在第一种情况下得到的错误是“错误:字段初始值设定项不是常量”,但我并没有真正理解。如果我尝试使用 std::function 它会变得更糟,因为它说:“在声明时不能由非常量表达式初始化”。

为什么 lambda 函数不是常量?我错过了什么吗?

最佳答案

当你构建 constexpr 对象时,你传递给它的所有东西都需要是一个核心常量表达式,[decl.constexpr]/9:

A constexpr specifier used in an object declaration declares the object as const. Such an object shall have literal type and shall be initialized. If it is initialized by a constructor call, that call shall be a constant expression (5.19).

并且,根据 [expr.const] lambda 不是常量表达式1:

A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (1.9), would evaluate one of the following expressions:

  • [...]
  • a lambda-expression (5.1.2);
  • [...]

但是,这仅适用于 constexpr 而不适用于 const,因此您可以简单地改为这样做:

static const MyStruct ops[6] = {
    {'+', [] (double a, double b) { return a+b; } },
    {'-', [] (double a, double b) { return a-b; } },
};

注意:您的 lambda 不需要捕获任何内容,因此您应该清空捕获列表 []


1作为dyp指出,有一个改变这个的建议:N4487

关于c++ - lambda 函数的静态数组 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30527865/

相关文章:

java - 使用 Lambda 部分展平 Java 中的嵌套集合

c++ - 从 C++ 调用带有可选参数的 Fortran 子例程

c++ - std::regex 转义在正则表达式中使用的特殊字符

Linux 四核 : single executable, 4 个进程

c++ - float 模板特化

java - 我对 Java Stream.flatMap 的理解正确吗?

java - C# IList.Where() 等同于 Java?

C++ - 从方法基类调用派生类中的重写方法

c++ - boost shared_array<char> 并从 char* 设置它

c++ - C++ 标准中的什么措辞允许 static_cast<non-void-type*>(malloc(N));去工作?