c++ - 用模板函数重载模板类

标签 c++ templates overloading

C++ 允许在一个命名空间中使用同名的类和函数:

struct S {};
void S() {}

在这种情况下,纯名称 S 表示函数 S。要改用 struct,您需要在 name 之前显式添加 struct

也可以制作函数模板,同时使用它们:

template <class T>
void S() {}

struct S {};

但是禁止使用模板结构

void S() {}

template <class T>
struct S {};

gives error像这样:

error: redefinition of 'S' as different kind of symbol

这是什么原因?为什么不允许在这里使用模板结构?是否存在在 S 之前使用显式关键字 struct (如非模板版本)如果允许的话无法解决名称冲突的情况?也许有提案存在?

最佳答案

C++ allows to use class and function with the same name in one namespace.

   struct S {};
   void S() {}

通常在声明 struct S 时,可以通过两种方式引用类型:Sstruct S。但这只是在您声明其他名为 S 的东西之前,例如,一个函数。当你这样做时,类型的名称不再是 S 了。它只是 struct S 而已。 S 这个名字是为函数保留的。

这样做是为了与 C 兼容。C 代码经常使用此设备。与 C++ 不同,C 将 struct 和 union 标记放置在与普通标识符不同的 namespace 中,并且 struct S 不能简单地称为 S

因此,为了能够编译使用该设备的 C 代码,C++ 对作为不同类型标识符重用的结构标记进行了异常(exception)处理。

由于 class 几乎是 struct 的同义词,因此 class 关键字也是如此。

但是C没有模板,不需要为它们提供向后兼容性,所以类模板没有这样的异常(exception)。

关于c++ - 用模板函数重载模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46434964/

相关文章:

c++ - 找到填充矩形的最少 MS Paint 操作数

c++ - 如何更改 C++ 中的第 n 个模板参数?

C++ 模板这可能吗?

c++ - 如何在 VS 2017 中编译其他编译器的代码

c++ - 处理大型数组时超出时间限制

c++ - 无法推断模板类成员的类型

C++17 std::shared_ptr<> 为类数组对象重载 operator[]

python - Django继承: how to have one method for all subclasses?

c++ - 链接错误 CString

c++ - 跨源文件模板实例化及使用