gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 14:00:28 26 4
gpt4 key购买 nike

阅读 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com