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

Default template argument deduction for copy initialization


C++17 has class template argument deduction. However, I was wondering whether it applies to statements like auto x = X() where X is a class template. Consider this code:

template <typename T = void>
struct X {};

int main() {       // all with -std=c++17
    X<> x0;        // compiles in both clang and gcc
    X x1;          // compiles in both clang and gcc
    auto x2 = X(); // compiles in clang but not gcc
    X<> x3 = X();  // compiles in clang but not gcc
}

Here is the godbolt link. So which compiler is right, and is this program valid C++17?


Solution

  • It's a bug in GCC.

    Notice that if you replace the parenthesis with curly braces the code compiles:

    auto x2 = X{}; // now compiles in clang and gcc
    X<> x3 = X{}; // now compiles in clang and gcc
    

    This is not class template argument deduction as there are no template arguments being deduced. Class template argument deduction should permit the elision of the template braces. The use of () or {} in this case should have no bearing on whether they are deduced.