4
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?

3 Answers 3

8

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
Sign up to request clarification or add additional context in comments.

Comments

6

(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.

6 Comments

Great answer +1. Where can I get a copy of the standard?
@JoshD : You can find it here (ISO/IEC 14882 2003 is C++03)
@JoshD: AFAIK you can't get it for free. However you can look at the drafts of the next standard.
Although, I would have liked (3) to be valid in case of function templates. We still have TAD (template argument deduction) to determine the trailing, non-defaulted template parameters.
@sellibitze in that case you can add a default class = void and it'll solve your problem.
|
4

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.