简体   繁体   English

为什么g++5在自动类型推导中推导对象而不是initializer_list

[英]Why does g++5 deduces object instead of initializer_list in auto type deduction

I recently came upon this code:我最近遇到了这个代码:

struct Foo{};

int main() 
{
    Foo a;
    // clang++ deduces std::initializer_list
    // g++5.1 deduces Foo
    auto b{a}; 
    a = b;
}

It compiles fine with g++5.1, but fails in clang++ (used both -std=c++11 and -std=c++14 , same results).它用 g++5.1 编译得很好,但在 clang++ 中失败(同时使用-std=c++11-std=c++14 ,结果相同)。 The reason is that clang++ deduces the type of b as std::initializer_list<Foo> , whereas g++5.1 deduces as Foo .原因是clang++ 将b的类型推导出为std::initializer_list<Foo> ,而g++5.1推导出为Foo AFAIK, the type should indeed be (counter-intuitive indeed) std::initializer_list here . AFAIK,类型确实应该是(确实违反直觉) std::initializer_list here Why does g++5 deduces the type as Foo ?为什么 g++5 将类型推导出为Foo

There is a proposal for C++1z that implements new type deduction rules for brace initialization ( N3922 ), and I guess gcc implemented them:有一个 C++1z 的提案,它为大括号初始化( N3922 )实现了新的类型推导规则,我猜 gcc 实现了它们:

For direct list-initialization:对于直接列表初始化:
1. For a braced-init-list with only a single element, auto deduction will deduce from that entry; 1.对于只有一个元素的braced-init-list,自动推导将从该条目中推导;
2. For a braced-init-list with more than one element, auto deduction will be ill-formed. 2. 对于一个多于一个元素的braced-init-list,自动推导将是格式错误的。

[Example: [例子:

 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] -- 结束示例]

Here is the gcc patch concerning the new changes with regards to "Unicorn initialization."这是关于“独角兽初始化”的新变化的gcc 补丁

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM