简体   繁体   中英

Access static data of non-template base of templated class

A template class is derived from non-template class that has static data member. Why can't I access that without specifying the template arguments? Actually, can I access any method or data in a template class without template arguments?

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. Template class must be generated with provided template argument first.

Why can't I access that without specifying the template arguments?

Because it's possible to write CTemplateClass so that it inherits from CNonTemplateBase only for some specific values of the template parameters.

Actually, can I access any method or data in a template class without template arguments?

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.

The compiler does not generate code to a template class without instantiation (of a type). Therefore, you cannot access a static member of an instantiation template class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM