简体   繁体   中英

c++ inherit from specialized template class

template<typename T1, typename T2, typename T3>
class A: public A<T1, T2, void> {
public:
    T1 a;
    T2 b;
    T3 c;

    void set() { a = aa; } // Cannot find variable `aa' here!
};

template<typename T1, typename T2>
class A<T1, T2, void> {
public:
    T1 aa;
    T2 bb;
};

As above, I have a template class A , and its partial specialized form A' . So is it possible for A to inherit from A'? According to g++, it seems OK. However, when I tried to access members in A', g++ started to complain: Fail to find that symbol. Anybody knows why?

As far as I remember you have to pull in aa to derived class with 'using'. Add the following (I do not remember exact syntax so forgive me any compilation issues) to your generic template:

using A<T1, T2, void>::aa;

EDIT: As Mehrdad noted this->aa should also work.

The name look up rules with C++ templates may seem a bit non-intuitive. When the compiler first parses the template definition, it resolves all names, which are not template-argument dependent . When it comes to template instantiation, it will resolve the rest.

If you take a look at the definition of class A only, there is no obvious dependence of the symbol aa on type arguments T1, T2 or T3. So the compiler tries to resolve the name, but it cannot, since that name is undefined in that environment.

So, to convince the compiler to do what you wanted, you have to use of the tricks below:

  • The easiest is probably this->aa . Since this has a template-argument dependent superclass, its members can only be looked up at template instantiation time, so everything is fine.

  • Qualify the member with the superclass, ie use A<T1, T2, void>::aa . This makes the dependency really obvious. You may also use the using directive, so that so do not have to type this every time.

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