c++ - 为什么派生类中有模板名(基类是模板的实例)?

标签 c++ templates using

我遇到了这段代码(使用基本类型进行了简化):

template <typename T>
class Base {
  T t;
};

class Derived : public Base<short> {
 public:
  using Base<short>::Base;
};

int main() {
  Derived::Base<long long> x;
  printf("%lu\n", sizeof(x));
  return 0;
}

它编译并工作(输出为 8,这是 long long 的大小)。看来我可以得到Base<T>对于任何类型 T使用 Derived::Base , 即使Derived只是 Base<short> 的一个子类. (在我遇到的代码中,Base 本身对 main 不可见。)

但是,我不太理解这种语法及其工作原理。

Derived::Base模板名称、类或函数(ctor)?这似乎是一个模板名称。模板名称是否在实例化此模板的所有类中都可用(例如模板名称 BaseBase<T> 中,对于所有类型 T)?我很困惑。对 cppreference 或 C++ 标准的任何解释或指针表示赞赏。

最佳答案

来自 en.cppreference.com/injected-class-name :

In the following cases, the injected-class-name is treated as a template-name of the class template itself:

  • it is followed by <
  • [..]

所以 Base里面Base<T>根据上下文,是类或模板名称。

关于c++ - 为什么派生类中有模板名(基类是模板的实例)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57244633/

相关文章:

c++ - 使用递归查找回文字符串?

c++ - 如何将模板化的结构/类声明为 friend ?

c++ - 是否可以将枚举注入(inject)类范围/命名空间?

linq - 在C#中使用Linq进行字符串替换

c++ - 多个类的共享模板成员函数

.net - 关闭读取器时,处置数据上下文会导致调用 Read 的尝试无效

php - 将数据从 C++ 传递到 PHP

android - 不能使用 typedef 枚举

c++ - 函数模板重载 - 特化

c# - 如何根据单元格背景颜色更改 WPF DataGrid 单元格小部件背景颜色?