c++ - 在构造函数中为类名添加和省略模板参数之间的区别

标签 c++ templates constructor typename injected-class-name

我想知道两者之间是否存在本质区别:

template <typename T> 
class foo{
  foo<T>(){};
};

template<typename T>
class foo{
  foo(){};
};

两者似乎都有效,但我不明白两者之间的区别。第一个让我很困惑,我不明白这里的 < T > 的作用是什么。

最佳答案

根据injected-class-name的规则,它们完全是同一回事。

$14.6.1/1 Locally declared names [temp.local] :

Like normal (non-template) classes, class templates have an injected-class-name (Clause [class]). 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 <>.

所以 foofoo<T>在这里指的是同样的事情。更具体地说,

The first one is confusing me, I don't understand what's the role of the < T > here.

您正在使用注入(inject)类名 foo及其模板参数 T (即 foo<T> ),它指的是模板类本身。

关于c++ - 在构造函数中为类名添加和省略模板参数之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40563997/

相关文章:

c++ - 两个3D点云变换矩阵

c++ - 从 txt 中获取大量数据并对其进行排序

c++ - 为什么 move 构造函数只被调用一次?

JavaScript:构造函数可以创建 documentElement 对象吗?

c++ - 找出数字之间的最大差异

c++ - 是否可以从 std::bind 对象访问参数?

Perl舞者: passing database info to template

c++ - 使用外部模板 (C++11)

C++ 可变参数模板空包

c++ - 在默认构造函数中初始化 vector 变量?