为什么模板名称在派生 class 中可用(基础 class 是模板的一个实例)?
Why is template name available in derived class (the base class is an instance of the template)?
我遇到了这段代码(使用基本类型进行了简化):
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的大小)。似乎我可以使用 Derived::Base
获得任何类型 T
的 Base<T>
,即使 Derived
只是 Base<short>
的子 class。 (在我遇到的代码中,Base
本身对 main
不可见。)
但是,我不太理解这种语法及其工作原理。
Derived::Base
是模板名称,还是class,还是函数(ctor)?这似乎是一个模板名称。模板名称是否在实例化此模板的所有 class 中可用(例如模板名称 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<T>
中的 Base
根据上下文,是 class 或模板名称。
我遇到了这段代码(使用基本类型进行了简化):
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的大小)。似乎我可以使用 Derived::Base
获得任何类型 T
的 Base<T>
,即使 Derived
只是 Base<short>
的子 class。 (在我遇到的代码中,Base
本身对 main
不可见。)
但是,我不太理解这种语法及其工作原理。
Derived::Base
是模板名称,还是class,还是函数(ctor)?这似乎是一个模板名称。模板名称是否在实例化此模板的所有 class 中可用(例如模板名称 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<T>
中的 Base
根据上下文,是 class 或模板名称。