c++ - 为什么将 X 而不是 X<T> 用于模板化构造函数和析构函数?

标签 c++ templates

在专业 C++(2e 第 689 页)中它说:

Only for constructors and the destructor you should use X and not X<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/

相关文章:

c++ - 有没有办法防止 vector 中的元素被破坏?

c++ - 如何为迭代器类型实现 operator->?

c++ - 访问冲突 : 0xC0000005, 为什么会发生这种情况?

C++模板类T麻烦

templates - 使用 Liquid 将名称大写,不适用于特殊字符

c++ - 纯功能,为什么没有优化?

c++ - 如何在 Qt 中使用两个键修饰符设置 3 键序列快捷方式?

javascript - 如何实现html页面的主题/模板加载

templates - VS2010 - 将模板添加到新项目窗口

ruby-on-rails - rails : render partial with selected controller and action in view