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
时,可以通过两种方式引用类型:S
和 struct 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/