λ什么时候是琐碎的? [英] When is a lambda trivial?

查看:86
本文介绍了λ什么时候是琐碎的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么时候可以保证lambda是琐碎的?

When is a lambda a guaranteed to be trivial, if ever?

我假设,如果仅捕获琐碎的类型或什么都不捕获,那将是琐碎的。我没有任何标准的支持。

I assumed that if it captures only trivial types or nothing, it would be trivial. I don't have any standard-ese to back that up though.

我的动机是将某些代码从Visual C ++ 12迁移到14,并发现某些静态断言在执行时失败

My motivation was in moving some code from Visual C++ 12 to 14 and discovered some static asserts failed when dealing with lambdas I assumed to be trivial.

示例:

#include <type_traits>
#include <iostream>
using namespace std;

int main()
{
    auto lambda = [](){};

    cout << boolalpha << is_trivially_copyable<decltype(lambda)>{} << endl;
}

这会产生 false 在vs140上,但在vs120和clang中 true 。由于没有gcc> = 5,我无法测试gcc。我希望这是vs140的回归,但是我不确定这里的正确行为。

This produces false on vs140 but true in vs120 and clang. I could not test gcc due to not having gcc >= 5 around. I expect this is a regression in vs140, but I'm not certain of the correct behavior here.

推荐答案

标准未指定闭包类型(lambda表达式的类型)是否为琐碎与否。它明确地将其留给实现,从而使其不可移植。恐怕您不能依靠您的 static_assert 产生一致的结果。

The standard does not specify whether a closure type (the type of a lambda expression) is trivial or not. It explicitly leaves this up to implementation, which makes it non-portable. I am afraid you cannot rely on your static_assert producing anything consistent.

引用C ++ 14(N4140)5.1 .2 / 3:

Quoting C++14 (N4140) 5.1.2/3:


...一个实现可能定义的闭包类型与以下描述不同,前提是这不会改变可观察到的程序的
行为,但不更改以下内容:


  • 程序的大小和/或对齐方式闭合类型,

  • 闭合类型是否可以被复制(第9章),

  • 闭合类型是否为标准布局类(第9条) ),或者

  • 关闭类型是否为POD类(第9条)。

  • the size and/or alignment of the closure type,
  • whether the closure type is trivially copyable (Clause 9),
  • whether the closure type is a standard-layout class (Clause 9), or
  • whether the closure type is a POD class (Clause 9).

...

(强调我的意思)

解析双重否定后在那句话中,我们可以看到实现被允许决定闭包类型是平凡可复制,标准布局还是POD。

After parsing the double negation in that sentence, we can see that the implementation is allowed to decide whether the closure type is trivially copyable, standard layout, or POD.

请注意,在C ++ 17(N4659)中,[expr.prim.lambda.closure] 8.1.5.1/2也存在相同的措辞。

Note that the same wording is also present in C++17 (N4659), [expr.prim.lambda.closure] 8.1.5.1/2.

这篇关于λ什么时候是琐碎的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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