3

I am trying to define the same template class in several version, each with a different template parameter. The compiler is giving me the error

 previous declaration ‘template<class T1> class A’ used 

Is there a way to circumvent this problem? Unfortunately I cannot use Cx++11 where I can assign a default template parameter. What is a good practice to tackle this issue? I am using old g++4.4.7

#include <iostream> template <class T1> class A{}; template <class T1,class T2> class A{}; int main() { return 0; } 
1
  • Kerrek has the right answer, but C++11 only added default template types to functions... you could always write template <typename T1, typename T2 = void> class A { }; Commented Nov 21, 2014 at 18:11

2 Answers 2

5

Make a variadic template and add partial specializations:

template <typename ...> class A; // leave primary template undefined template <typename T> class A<T> { // ... }; template <typename T1, typename T2> class A<T1, T2> { // ... }; 
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Kerrek. Good stuff the partial specialization! Sorry that I can't use variadic templates, but I like the response.
3

If you cannot use C++11 variadic templates, you can use a "mock" type

struct NoType{}; template <class T1, class T2 = NoType> // or class T2 = void, doesn't really matter class A{}; 

then specialize it as needed.

PS: as @Barry mentioned in the comment, default template parameters for classes ARE ALLOWED in pre C++11 . The novelty in this respect introduced by C++11 is to allow default template parameters in functions.

1 Comment

Hi. This is ok ..it is meant/works well to be used with Partial Specialization.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.