Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default template argument of a class template has no effect if placed after the definition of that class template

Please consider the following example:

// Mind the default template argument
template <typename T = int>
struct Test;

template <typename T>
struct Test
{
};

template <typename T>
struct Test;

int main()
{
    Test<>       t;
    return 0;
}

The code above can be successfully compiled by MSVC 19, gcc 8 and clang 8. Just as expected.
Now let's move the default template argument to the definition of the class template:

template <typename T>
struct Test;

// Mind the default template argument
template <typename T = int>
struct Test
{
};

template <typename T>
struct Test;

int main()
{
    Test<>       t;
    return 0;
}

This works with all three compilers, too.

However, if I placed the default argument after the definition of the Test class template, then Visual Studio would refuse to compile the source and complain that

line marked (!): too few template arguments

template <typename T>
struct Test;

template <typename T>
struct Test
{
};

// Mind the default template argument
template <typename T = int>
struct Test;

int main()
{
    Test<>       t;    // (!)
    return 0;
}

Is it a MSVC bug?
I think cppreference is quite clear on the subject: default template arguments on the definition and all declarations should be merged. No special exception is made for the declarations following the definitions, right?

like image 263
Igor G Avatar asked Jun 18 '19 13:06

Igor G


1 Answers

This is a bug. Per [temp.param]/12

The set of default template-arguments available for use is obtained by merging the default arguments from all prior declarations of the template in the same way default function arguments are ([dcl.fct.default]).

Since t comes after

// Mind the default template argument
template <typename T = int>
struct Test;

the int default parameter should be considered and used since no parameter is specified.

like image 68
NathanOliver Avatar answered Oct 24 '22 06:10

NathanOliver