Why does g++5 deduces object instead of initializer_list in auto type deduction
Asked Answered
T

1

7

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). 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?

Tavia answered 2/5, 2015 at 21:28 Comment(9)
What compiler flags are you using?Teatime
@Teatime I tried both -std=c++11 and -std=c++14Tavia
In that case, it is a compiler bug.Teatime
Anyway, you should put that kind of information in the question. It kind of invlidates the answer.Teatime
@Teatime Added, although I marked the question with c++11Tavia
@juanchopanza: Is it?Colima
@LightnessRacesinOrbit If -std-c++11 or -std=c++14 are used, then I'd say yes.Teatime
See N3922. In particular, "Direction from EWG is that we consider this a defect in C++14."Nomenclature
@vaxquis That's not a dupe. As I mentioned in the question, I knew that the type should be initializer_list. The rules changed a bit as mentioned in the answer.Tavia
L
13

There is a proposal for C++1z that implements new type deduction rules for brace initialization (N3922), and I guess gcc implemented them:

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.

[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."

Lachesis answered 2/5, 2015 at 21:34 Comment(1)
LOL @ "unicorn initialization". So much better than "uniform".Nomenclature

© 2022 - 2024 — McMap. All rights reserved.