Class template with multiple template parameters

I am trying to define the same template class in multiple versions, each with a different template parameter. The compiler tells me the error

 previous declaration โ€˜template<class T1> class Aโ€™ used

      

Is there a way to get around this problem? Unfortunately I cannot use Cx ++ 11 where I can assign a default template parameter. What is good practice for solving this problem? 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; }

      

+3


source to share


2 answers


If you cannot use C ++ 11 variadic templates you can use the "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. A novelty in this regard introduced by C ++ 11 is to allow default template parameters in functions.

+3


source


Make a variational template and add partial specialization:



template <typename ...> class A;      // leave primary template undefined

template <typename T> class A<T>
{
    // ...
};

template <typename T1, typename T2> class A<T1, T2>
{
    // ...
};

      

+5


source







All Articles