lambda作为静态成员 [英] lambda as a static member

查看:211
本文介绍了lambda作为静态成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用lambda作为静态成员,像这样:

I'm trying to use a lambda as a static member, like this:

struct A
{
    static constexpr auto F = [](){};
};


int main()
{
    A::F();
    return 0;
}

这是否是正确的C ++ 11代码?在clang,我得到这个错误:

Is this even correct C++11 code? On clang, I get this error:

error: constexpr variable 'F' must be initialized by a constant
      expression
    static constexpr auto F = [](){};
                              ^~~~~~

似乎在clang,lambdas不被认为是常数表达式。它是否正确?也许他们没有完全实现lambdas尚未铛,因为gcc 4.7似乎允许它作为 constexpr ,但它给出另一个错误:

It seems in clang, lambdas aren't considered a constant expression. Is this correct? Perhaps they haven't fully implemented lambdas yet in clang because gcc 4.7 seems to allow it as a constexpr, but it give another error:

error: ‘constexpr const<lambda()> A::F’, declared using local type ‘const<lambda()>’, is used but never defined


$ b b

我不确定,我明白这是什么意思。它似乎正确地推导了lambda的类型,但它只声明它,而不是定义它。我将如何定义它?

I'm not sure, I understand what that means. It seems to correctly deduce the type of the lambda, but it only declares it and not define it. How would I go about defining it?

推荐答案

此代码是错误的。需要通过常量表达式初始化 constexpr 变量, [expr.const] p2 说: p>

This code is ill-formed. A constexpr variable is required to be initialized by a constant expression, and [expr.const]p2 says:


是一个核心常量表达式,除非它包含以下其中一个作为潜在求值的子表达式[...]:

A conditional-expression is a core constant expression unless it involves one of the following as a potentially evaluated subexpression [...]:


  • a < $ b
  • a lambda-expression

因此,GCC不接受此代码。

GCC is therefore incorrect to accept this code.

一种方法给类一个lambda类型的静态数据成员:

Here's one way to give a class a static data member of lambda type:

auto a = []{};
struct S {
  static decltype(a) b;
};
decltype(a) S::b = a;

这篇关于lambda作为静态成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆