c++ - 为什么不能重载类模板?

标签 c++ templates overloading template-specialization language-lawyer

阅读 this question让我想知道:是否有不允许类模板重载的技术原因?

通过重载,我的意思是有几个具有相同名称但参数不同的模板,例如

template <typename T>
struct Foo {};

template <typename T1, typename T2>
struct Foo {};

template <unsigned int N>
struct Foo {};

编译器设法处理重载的函数和函数模板,难道不能将相同的技术(例如名称修改)应用于类模板吗?

起初,我认为单独使用模板标识符可能会导致一些歧义问题,但唯一可能发生的情况是在将其作为模板模板参数传递时,因此参数的类型可用于选择合适的重载:

template <template <typename> class T>
void A {};

template <template <unsigned int> class T>
void B {};

A<Foo> a; // resolves to Foo<T>
B<Foo> b; // resolves to Foo<N>

您认为这样的功能有用吗?是否有一些“好的”(即技术)原因导致这在当前的 C++ 中是不可能的?

最佳答案

模板完整指南 (Amazon) 的第 12.5 节包含以下引用:

You may legitimately wonder why only class templates can be partially specialized. The reasons are mostly historical. It is probably possible to define the same mechanism for function templates (see Chapter 13).

In some ways the effect of overloading function templates is similar, but there are also some subtle differences. These differences are mostly related to the fact that the primary template needs to be looked up when a use is encountered. The specializations are considered only afterward, to determine which implementation should be used.

In contrast, all overloaded function templates must be brought into an overload set by looking them up, and they may come from different namespaces or classes. This increases the likelihood of unintentionally overloading a template name somewhat.

Conversely, it is also imaginable to allow a form of overloading of class templates. Here is an example:

// invalid overloading of class templates
template<typename T1, typename T2> class Pair; 
template<int N1, int N2> class Pair; 

However, there doesn't seem to be a pressing need for such a mechanism.

此外,C++ 的设计和演变(Amazon)在第 15.10.3 节中包含此引用

I therefore concluded that we needed a mechanism for "specializing" templates. This could be done either by accepting general overloading or by some more specific mechanism. I chose a specific mechanism because I thought I was primarily addressing irregularities caused by irregularities in C and because suggestions of overloading invariably creates a howl of protests. I was trying to be cautious and conservative; I now consider that a mistake. Specialization as originally defined was a restricted and anomalous form of overloading that fitted poorly with the rest of the language.

我的大胆强调。我将其解释为函数重载解决方案比类特化更难实现(并且用户正确)。所以可能没有真正的技术障碍(类似于函数模板部分特化),而是一个历史事故。

关于c++ - 为什么不能重载类模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11968994/

相关文章:

java - 方法重载中也存在多态性吗?

c++ - 动态内存分配/利用未使用的内存

c++ - 将 SFML 的 RenderWindow 对象传递给模板函数

c++ - 从哪里获得最新的 OpenGL32.lib?

C++ 17 : Using alias template bug in gcc?

php - 在 Woocommerce 3.5 中删除购物车表上的运费估算消息

java - 在方法重载中返回

c++ - 除了++ 和 -- 之外,是否可以重载后缀一元运算符?

c++ - 有没有办法将 std::stack<pointer> 转换为 std::stack<const pointer>?

c++ - 如何在 C++ 中使用比较运算符比较日期和时间