6

Sometime I want to write two templates like:

template <typename Type1>
class A{
    ...
};

template <typename Type1, typename Type2>
class A{
    ...
};

But it seems that it is illegal to have two templates shared the same name but have different parameters. I have to name it like A_1, A_2. I think it might be useful if I can do this especially when implementing Functors.

Why C++ doesn't allow this? Does it difficult to implement or have ambiguity in some circumstance? Will this be supported on later version of C++?

StarPinkER
  • 14,081
  • 7
  • 55
  • 81

2 Answers2

13

It is extremely useful, but like you say, C++ doesn't allow you to do this directly. However, you can do almost the same thing with partial specialisation.

This is particularly easy if you use variadic templates in C++11, as you can do the following:

template <typename... T>
struct A; // Declared but not defined

template <typename T, typename U>
struct A<T, U>
{
    // definition of the two-parameter case
};

template <typename T>
struct A<T>
{
   // definition of the one-parameter case
};

Effectively, this allows you to have A<T, U> and A<T> as completely separate types. Attempting to instantiate an A with more template parameters will lead to a compile error as the general case is undefined (you could use a static_assert to give a nice error message if you wanted).

Something similar can be achieved in C++03 using default template parameters (set to an empty dummy struct, or void), but the C++11 version is much nicer IMO.

Tristan Brindle
  • 16,281
  • 4
  • 39
  • 82
0

One simple (possible) solution, would be to have default value for the second template argument. this way you only implement one template, and you can call it with one template argument, and use the default second, or, override the default.

yosim
  • 503
  • 2
  • 8