我遇到了这段代码(使用基本类型进行了简化):
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)?这似乎是一个模板名称。模板名称是否在实例化此模板的所有类中都可用(例如模板名称 Base
在 Base<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/