c++ - 静态(可能是 constexpr)数据成员 l​​ambda

标签 c++ lambda static c++14 data-members

以下代码无法编译:

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 数据成员 l​​ambda?

最佳答案

关于静态数据成员的规则在[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). A static data member of literal type can be declared in the class definition with the constexpr 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)数据成员 l​​ambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42799268/

相关文章:

c++ - "construct on first use"习语在任何情况下都会失败吗?

c - 在汇编代码中,静态局部 C 变量后跟一个数字。这个数字是随机的吗?

c++ - 多线程无法按预期工作

c++ - 为什么我的 vector 大小一直重置为 0? (目前正在使用类(class))

c++ - 在eclipse(kepler)中用于c++开发的插件

c# - 如何在 C# 中将列标题添加到 ListView

javascript - 正则表达式:在一个第一次出现和另一个最后一次出现之间获取

c++ - 如何静态编译 wxwidgets 应用程序?

分层窗口上的 C++ GDI+ 绘图图像不起作用

c++ - 在没有 std::function 的情况下将 lambdas/函数存储在 std::vector 中