重新定义lambdas不允许在C ++ 11,为什么? [英] Redefining lambdas not allowed in C++11, why?

查看:153
本文介绍了重新定义lambdas不允许在C ++ 11,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

#include <functional>

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

  return 0;
}

这将在gcc 4.7.2中发出以下错误消息:

This emits the following error message in gcc 4.7.2:

test.cpp: In function ‘int main()’:
test.cpp:5:13: error: no match for ‘operator=’ in ‘test = <lambda closure object>main()::<lambda()>{}’
test.cpp:5:13: note: candidate is:
test.cpp:4:16: note: main()::<lambda()>& main()::<lambda()>::operator=(const main()::<lambda()>&) <deleted>
test.cpp:4:16: note:   no known conversion for argument 1 from ‘main()::<lambda()>’ to ‘const main()::<lambda()>&’

从标准5.1.2.3(强调我):

From the standard 5.1.2.3 (emphasis mine):


一个实现可以不同于下面描述的定义闭包类型,只要这不改变程序的可观察行为,除非改变:

An implementation may define the closure type differently from what is described below provided this does not alter the observable behavior of the program other than by changing:

- 闭包类型的大小和/或对齐方式,

— the size and/or alignment of the closure type,

- 闭包类型是否可轻易复制(第9条)

— whether the closure type is trivially copyable (Clause 9)

- 闭包类型是否是标准布局类(第9条),

— whether the closure type is a standard-layout class (Clause 9), or

- 闭包类型是否为POD类(第9条)。

— whether the closure type is a POD class (Clause 9).

据我所知,反对。它试图使用已删除的分配运算符和失败。我很想知道是否有一个简单的解决方法,更广泛地说,允许复制可构造性通常省略lambdas的动机理由。

As far as I can tell, this is what I'm running up against. It's attempting to use a deleted assignment operator and failing. I am curious to know if there's an easy workaround, and more broadly what the motivating rationale for allowing copy constructibility to be omitted for lambdas generally.

推荐答案

你似乎认为这两个lambdas有相同的类型,但这不是真的。每个都创建自己的类型:

You seem to think that those two lambdas have the same type, but that is not true. Each one creates its own type:

#include <functional>
#include <type_traits>
#include <iostream>

int main() {
  auto test = []{};
  auto test2 = []{};
  std::cout << std::is_same< decltype( test ), decltype( test2 ) >::value << std::endl;
  return 0;
}

将打印 0 。当然,你从编译器得到的错误消息可能在这方面有点清楚...

will print 0. Of course the error message you are getting from the compiler could be a little bit clearer in this regards...

这篇关于重新定义lambdas不允许在C ++ 11,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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