在专业 C++(2e 第 689 页)中它说:
Only for constructors and the destructor you should use
X
and notX<T>
.
所以:
template<typename T>
class X{
X(); // X
~X(); // X
X<T>& operator=(const X<T>& rhs); // X<T>
};
为什么不应该使用 X<T>
构造函数和析构函数声明?
最佳答案
引用很简单,错误。
X<T>
是类型的实际名称:
[C++11: 14.2/6]:
A simple-template-id that names a class template specialization is a class-name (Clause 9).
……你可以在任何地方使用它:
template<typename T>
class X
{
public:
X<T>() {}
~X<T>() {}
X<T>& operator=(const X<T>& rhs) {}
};
int main()
{
X<int> x;
}
( live demo )
您可以选择使用 X
作为“速记”,模板参数将自动为您附加(有点):
[C++11: 14.6.1/1]:
Like normal (non-template) classes, class templates have an injected-class-name (Clause 9). The injected-class-name can be used as a template-name or a type-name. When it is used with a template-argument-list, as a template-argument for a template template-parameter, or as the final identifier in the elaborated-type-specifier of a friend class template declaration, it refers to the class template itself. Otherwise, it is equivalent to the template-name followed by the template-parameters of the class template enclosed in<>
.
…但它肯定不是任何地方必需的。
听起来作者正在尝试执行样式指南,但并没有充分说明这完全取决于您。
关于c++ - 为什么将 X 而不是 X<T> 用于模板化构造函数和析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24479553/