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

vso*_*tco 7 c++ auto c++11 clang++ gcc5

我最近发现了这段代码:

struct Foo{};

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

它用g ++ 5.1编译得很好,但是在clang ++中失败了(使用了两个-std=c++11-std=c++14相同的结果).其原因是,铛++推导的类型bstd::initializer_list<Foo>,而g++5.1推导出作为Foo.据我所知,类型确实应(反直觉确实)std::initializer_list在这里.为什么g ++ 5推断出类型Foo

Bar*_*rry 13

有一个C++ 1z的提议,它实现了大括号初始化的新类型推导规则(N3922),我猜gcc实现了它们:

对于直接列表初始化:
1.对于只有一个元素的braced-init-list,自动扣除将从该条目推导出来;
2.对于具有多个元素的braced-init-list,自动扣除将是错误的.

[例:

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. 
Run Code Online (Sandbox Code Playgroud)

- 结束例子]

这是关于"Unicorn初始化"的新变化的gcc补丁.

  • LOL @"独角兽初始化".比"制服"好得多. (2认同)