7

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?

Niall
  • 30,036
  • 10
  • 99
  • 142
Praveen
  • 8,945
  • 4
  • 31
  • 49
  • If my memory serves me well, there was a change (maybe even a late change) in the spec between C++11 and C++14 in this area - I'll try find a link for it. – Niall Jul 09 '15 at 06:59
  • Noteworthy is that C++14 support in clang3.6 is definitely "not complete", and I expect that the same applies for gcc 4.9 - possibly also 5.0. So if it's "something late in the spec" or just "something nobody had implemented yet", it may well be changing in new releases. – Mats Petersson Jul 09 '15 at 07:13

1 Answers1

8

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.

Community
  • 1
  • 1
Niall
  • 30,036
  • 10
  • 99
  • 142
  • 3
    And clang as of last week (july 2nd) still treats it as `initializer_list` - with a warning that "initalization of a variable with deduced type should use = for assignment". – Mats Petersson Jul 09 '15 at 07:15
  • Clang warns that "meaning of `auto{expr}` will change in a future version", presumably to the behaviour we all expected all along" – underscore_d Feb 25 '16 at 19:38