Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

auto and brace initialization in C++11/C++14 [duplicate]

When I compile the below code with clang and gcc T is deduced differently.

#include<initializer_list> //for clang

//to see how T is deduced(form compiler error).
template<typename T>
void foo(T);

int main() {
    auto var1{2};
    foo(var1);
}

Here is what I got.

clang 3.6(c++11/c++14)
gcc 4.9(c++11/c++14) 
T = std::initializer_list<int>

gcc 5.1(c++11/c++14)
T = int

I think T should be std::initializer_list<int>.

Why is T = int in gcc 5.1?

like image 292
Praveen Avatar asked Jul 09 '15 06:07

Praveen


1 Answers

This is proposed change to the C++17 specification - N3922 (I'm not sure if it has been accepted yet).

Basically this presentation from Scott Meyers, slide 20 covers the new rules.

auto var1 {2} ;

Here, var1 will be deduced to be an int.

It does look like some compilers have already implemented the change. I believe the change is more "intuitive" but your mileage may vary. I think in this interim phase, prefer the = initialisation, it may be more portable.

The answer here has some more detail on the history of the proposals and defects raised.

like image 144
Niall Avatar answered Nov 08 '22 09:11

Niall