以下代码无法编译:
struct object
{
static constexpr auto f;
};
constexpr auto object::f = [](auto&& x){x += 1;};
这两个都不是:
struct object
{
static constexpr auto f = [](auto&& x){x += 1;};
};
但是这样做(当 f
不是成员时):
static constexpr auto f = [](auto&& x){x += 1;};
有没有办法在 C++14 中声明和定义静态 constexpr 数据成员 lambda?
最佳答案
关于静态数据成员的规则在[class.static.data]中:
If a non-volatile
const
static
data member is of integral or enumeration type, its declaration in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression (5.19). Astatic
data member of literal type can be declared in the class definition with theconstexpr
specifier; if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression.
只能在类定义中定义static const
整数/枚举类型或constexpr
成员。 C++14 不允许使用 constexpr
lambdas 句点。 [expr.const] 中的措辞用于读取:
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);
— [...]
所以在 C++14 中,你不能有一个静态的 lambda 数据成员——你不能内联定义它,也不能外联定义它,因为你没有办法声明它(声明的变量使用 auto
需要初始化程序)。你真倒霉。
在 C++17 中,我们可以使用 constexpr
lambda 多亏了 p0170 ,此时您的第二个选项就可以了:
struct object
{
static constexpr auto f = [](auto&& x){x += 1;};
};
关于c++ - 静态(可能是 constexpr)数据成员 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42799268/