我想做这样的事情(在类里面):
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 asconst
. 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/