使用大括号聚合初始化 [英] Aggregate initialization with curly braces

查看:635
本文介绍了使用大括号聚合初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 11中,允许使用大括号语法复制聚合?我有以下代码:

  struct s 
{
int x;
};
template< class T>
struct holder
{
template< class A>
持有人(A&& x):t {x} {}
T t;
};

以下每个语句都有效。

  auto s1 = s {1}; 
auto s2(s1);
auto s3 {s1}; ///注意:这个工程!但是,下面的第二个语句引发了错误无法将's'转换为's' 'int'in initialization

  holder< s& h {5}; 
持有人< s> h1 {s {5}};

我使用gcc 4.8.2。为什么会出现这个错误?

解决方案

在C ++ 11中,当类型 code>是一个聚合类型,使用 {...} 进行初始化。聚合初始化始终初始化 T 的成员,而不是 T 本身。



虽然这正是标准所要求的,但这是不必要的,这就是为什么在未来的标准中,规则将可能被改变为从相同类型进行初始化的特殊例外。 这是核心语言问题1467. p>

到那个时候,不幸的是,你得到的错误是完全正确的,你必须解决它。


In C++11, are the aggregates allowed to be copied with curly-braces syntax? I have the following code:

struct s
{
    int x;
};
template<class T>
struct holder
{
    template<class A>
    holder(A&& x) : t{x} {}
    T t;
};

Each one of the statements below works.

auto s1 = s{1};
auto s2(s1);
auto s3{s1}; ///NOTE : this works!

However, the second statement below raises the error cannot convert 's' to 'int' in initialization.

holder<s> h{5};
holder<s> h1{s{5}};

I am using gcc 4.8.2. Why do I get this error?

解决方案

In C++11, when a type T is an aggregate type, initialisation using { ... } performs aggregate initialisation. Aggregate initialisation always initialises the members of T, not T itself.

Although this is exactly what the standard requires, this is unwanted, which is why in a future standard, the rule will likely be changed to make a special exception for initialisation from the same type. This is core language issue 1467.

Until that time, unfortunately, the error you are getting is entirely correct, and you will have to work around it.

这篇关于使用大括号聚合初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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