Lambda捕获constexpr对象 [英] Lambda capturing constexpr object

查看:127
本文介绍了Lambda捕获constexpr对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

GCC 4.7.2编译此:

GCC 4.7.2 compiles this:

constexpr int i = 5;
[]{ std::integral_constant< int, i >(); }; // nonstandard: i not captured

但不是这样:

constexpr int i = 5;
[&i]{ std::integral_constant< int, i >(); }; // GCC says i not constexpr

后面的例子对我来说是正确的,根据C ++ 11 §5.1.2/ 15:

The latter example appears correct to me, according to C++11 §5.1.2/15:


如果实体被隐式或显式捕获,但未被副本捕获,未指定在引用捕获的实体的闭包类型中是否声明了其他未命名的非静态数据成员。

An entity is captured by reference if it is implicitly or explicitly captured but not captured by copy. It is unspecified whether additional unnamed non-static data members are declared in the closure type for entities captured by reference.

lambda中的对象 i 是指包含范围中的变量,即 constexpr ,而不仅仅是 const 引用。

It seems the captured object i inside the lambda refers to the variable in the enclosing scope, which is constexpr, not merely a const reference.

标准明确说明,使用by-value捕获转换为使用相应的成员的lambda对象。我认为5.1.2提示我的解释是正确的。

The standard explicitly says that the use of a by-value capture is transformed into a use of the corresponding member of the lambda object. And I think that 5.1.2 hints that my interpretation is correct.

有没有明确说明引用的捕获是指包含范围中的对象还是a

Is there anything that explicitly says that whether a capture by reference refers to the object in the enclosing scope or a reference?

推荐答案

第二个模板参数 std :: integer_constant< int,i> 用于非类型表单的模板参数,特别是整数或枚举类型(14.3.2p1 bullet 1),因此必须是 int 类型的转换常量表达式。

The second template-argument to std::integral_constant< int, i > is for a template-parameter of non-type form, specifically of integral or enumeration type (14.3.2p1 bullet 1) and so must be a converted constant expression of type int.

lambda-expression ,当在复合语句(5.1.2p11)中使用odr时发生隐式捕获;在显式模板实例化中使用转换后的常量表达式不是odr-use(3.2p3),所以第一个例子是有效的。

In a lambda-expression, implicit capture occurs when an entity is odr-used in the compound statement (5.1.2p11); use of a converted constant expression in an explicit template instantiation is not odr-use (3.2p3), so the first example is valid.

gcc是不正确的拒绝它; 5.1.2p17在注释中说:

In the second example, I think gcc is incorrect to reject it; 5.1.2p17 says in a note that:


不是odr使用的 id-expression

尽管该段落作为一个整体讨论了拷贝捕获,但是没有理由不应用这条规则来捕获参考。这是不奇怪的,标准是不清楚这一点;实际上没有理由捕获可以通过引用在转换后的常量表达式中使用的实体。

Although the paragraph as a whole is discussing capture by copy, there's no reason not to apply this rule to capture by reference as well. It's unsurprising that the standard is unclear on this; there's really no reason to capture an entity that can be used in a converted constant expression by reference.

这篇关于Lambda捕获constexpr对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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