Search code examples
c++language-lawyerc++17template-argument-deduction

Template parameter deduction for constructors from initializer list


At the Kona meeting, template parameter deduction for constructors (P0091R0) has been approved. It simplifies some variable definitions:

std::pair   p  {1,2};     // o.k., constructor pair<int,int>(1,2)
std::vector v1 (10, 0);   // o.k., 10 zeroes, constructor vector<int>(size_t n, T initvalue)
std::vector v2 {10, 0};   // o.k., 2 values: 10, 0, apparently initializer list?
std::vector v3 = {10, 0}; // o.k., same as v2?

However, the following lines do not compile in gcc 7 HEAD 201611 version (live example):

std::vector v4 = {3};     // error: no matching function for call to 'std::vector(int)'
std::vector v5 {1, 2, 3}; // error: 'int' is not a class
std::set    s  {1, 2, 3}; // error: no matching function for call to 'std::set(int,int,int)'

Are these just "a bridge too far", since they involve initializer lists? Are they covered by template type parameter deduction? Will they be allowed, when compilers conform to C++1z?


Solution

  • You need an extra pair of curly braces to make your code work correctly:

    std::vector v4 = {{1, 5}}; 
    std::vector v5 {{1, 2, 3}};  
    std::set    s  {{1, 2, 3}};