为什么g ++ 5在自动类型推导中推导对象而不是initializer_list [英] Why does g++5 deduces object instead of initializer_list in auto type deduction
问题描述
我最近看到这段代码:
struct Foo{};
int main()
{
Foo a;
// clang++ deduces std::initializer_list
// g++5.1 deduces Foo
auto b{a};
a = b;
}
它使用g ++ 5.1编译正常,但在clang ++ -std = c ++ 11
和 -std = c ++ 14
,结果相同)。原因是 clang ++会将 b
的类型推断为 std :: initializer_list< Foo>
,而 g ++ 5.1
推断为 Foo
。 AFAIK,类型确实应该是(反直觉的) std :: initializer_list
这里。为什么g ++ 5推导类型为 Foo
?
It compiles fine with g++5.1, but fails in clang++ (used both -std=c++11
and -std=c++14
, same results). The reason is that clang++ deduces the type of b
as std::initializer_list<Foo>
, whereas g++5.1
deduces as Foo
. AFAIK, the type should indeed be (counter-intuitive indeed) std::initializer_list
here. Why does g++5 deduces the type as Foo
?
推荐答案
有一个建议C ++ 1z实现括号初始化的新类型扣除规则( N3922 ),我想gcc实现了它们:
There is a proposal for C++1z that implements new type deduction rules for brace initialization (N3922), and I guess gcc implemented them:
对于直接列表初始化:
1.对于只有一个元素的braced-init列表,自动扣除将从该条目中推导出;
2.对于具有多个元素的支撑初始列表,自动扣除将无效。
For direct list-initialization:
1. For a braced-init-list with only a single element, auto deduction will deduce from that entry;
2. For a braced-init-list with more than one element, auto deduction will be ill-formed.
[示例:
auto x1 = { 1, 2 }; // decltype(x1) is std::initializer_list<int>
auto x2 = { 1, 2.0 }; // error: cannot deduce element type
auto x3{ 1, 2 }; // error: not a single element
auto x4 = { 3 }; // decltype(x4) is std::initializer_list<int>
auto x5{ 3 }; // decltype(x5) is int.
- 结束示例]
-- end example]
这里是 gcc patch 关于Unicorn初始化的新更改。
Here is the gcc patch concerning the new changes with regards to "Unicorn initialization."
这篇关于为什么g ++ 5在自动类型推导中推导对象而不是initializer_list的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!