Why does C ++ not allow template overloading?

Someday I want to write two templates, for example:

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

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

Why does C ++ not allow this? Is it difficult to introduce or have ambiguity in some circumstances? Will this be supported in a later version of C ++?

+6
source share
2 answers

This is very useful, but as you say, C ++ does not allow you to do this directly. However, you can do almost the same with partial specialization.

This is especially convenient if you use variable templates in C ++ 11, since 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 create an instance of A with a large number of template parameters will result in a compilation error, since the general case is undefined (you could use static_assert to give a good error message if you want).

Something similar can be achieved in C ++ 03 using the default template options (set to an empty dummy structure or void ), but C ++ 11 is much better than IMO.

+12
source

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

0
source

All Articles