5

I understand (here is one source) that one can re-define default template arguments as long as the two definitions are not in conflict. So, I am trying to compile the following with g++ 5.3.1:

template <class = int> class A; // forward declaration
template <class T = A<>> struct B {};

template <class T = int> class A {}; // "= int" here is for clarity

int main() { return 0; }

The compiler complains:

error: redefinition of default argument for ‘class T’

Where is my understanding incorrect?

Community
  • 1
  • 1
AlwaysLearning
  • 7,257
  • 4
  • 33
  • 68

1 Answers1

4

You cannot redefine default template parameters.

When you write template <class T = int> class A {}; you are redefining this default parameter and that is why you get the error. You must choose one place to put that default parameter (either the forward declaration or the actual definition).

Rerito
  • 5,886
  • 21
  • 47
  • 1
    You can have several declarations of the same function but with different default parameters (in different scope). – Jarod42 Jul 18 '16 at 13:28
  • @Jarod42 that's right, but then you are not redefining the default parameters since the ones from the other scope aren't available to you in that context! – Rerito Jul 18 '16 at 13:35
  • This is a problem for the given example. The default argument is needed in the forward declaration to enable `A<>` in the definition of `B`. It is needed in the following definition of `A` (which is actually located in another file) for clarity... Is there a work-around to maintain the desired clarity of code? – AlwaysLearning Jul 18 '16 at 13:48
  • @Jarod42 I was not aware of that one, edited out the incorrect analogy then :) – Rerito Jul 18 '16 at 14:57