Roger Jones
Roger Jones

Reputation: 41

Default type parameter error in template code

1)template <class T = int, class U = double> //compiles

2)template <class T, class U =double> //compiles

3)template <class T = int, class U> //fails

Why does 1 and 2 compile whereas 3 does not?

Upvotes: 4

Views: 125

Answers (3)

UncleBens
UncleBens

Reputation: 41331

If you put that into some context, the third way may actually be legal, provided that the second default has been given earlier.

template <class T, class U = double>
struct X;

template <class T = int, class U> //here
struct X {};

int main()
{
    X<> x;
    X<float> y;
    X<char, char> z;
}

Upvotes: 4

Yakov Galka
Yakov Galka

Reputation: 72479

For the same reason why:

void f(int = 0, int);

fails.

There is no way to use 3rd version default parameter:

template<class T = int, class U> class B { ... };

B<, short> var; // ??? no such syntax

Upvotes: 8

Prasoon Saurav
Prasoon Saurav

Reputation: 92864

(3) is ill-formed because

C++03 [Section 14.1/11] says

If a template-parameter has a default template-argument, all subsequent template-parameters shall have a default template-argument supplied.

Upvotes: 6

Related Questions