[英]Access static data of non-template base of templated class
A template class is derived from non-template class that has static data member.模板 class 派生自具有 static 数据成员的非模板 class。 Why can't I access that without specifying the template arguments?
为什么我不能在不指定模板 arguments 的情况下访问它? Actually, can I access any method or data in a template class without template arguments?
实际上,我可以在没有模板 arguments 的情况下访问模板 class 中的任何方法或数据吗?
class CNonTemplateBase{
public:
static int some_data;
};
int CNonTemplateBase::some_data = 10;
template<typename T> class CTemplateClass : public CNonTemplateBase{};
...
...
int a = CTemplateClass<int>::some_data; //OK
int b = CTemplateClass::some_data; //ERROR
It's because CTemplateClass
doesn't exist on it's own.这是因为
CTemplateClass
本身并不存在。 Template class must be generated with provided template argument first.模板 class 必须首先使用提供的模板参数生成。
Why can't I access that without specifying the template arguments?
为什么我不能在不指定模板 arguments 的情况下访问它?
Because it's possible to write CTemplateClass
so that it inherits from CNonTemplateBase
only for some specific values of the template parameters.因为可以编写
CTemplateClass
以便它仅针对模板参数的某些特定值从CNonTemplateBase
继承。
Actually, can I access any method or data in a template class without template arguments?
实际上,我可以在没有模板 arguments 的情况下访问模板 class 中的任何方法或数据吗?
No, because they could depend on the template parameters.不,因为它们可能取决于模板参数。
In the end, this is simply how the langauge works.最后,这就是语言的工作方式。 I assume it would be possible to change the language to permit the syntax you want under certain conditions, but it'd make C++ even more complex without a good reason.
我认为在某些条件下可以更改语言以允许您想要的语法,但它会使 C++ 更加复杂而没有充分的理由。
The compiler does not generate code to a template class without instantiation (of a type).编译器不会为没有实例化(类型)的模板 class 生成代码。 Therefore, you cannot access a static member of an instantiation template class.
因此,您无法访问实例化模板 class 的 static 成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.