简体   繁体   中英

Inheritance with template classes

I'm trying to figure out, how can I inherit from template class to template class. The problem is: I can't use protected members of Parent class.

Example:

template <class N>
class Parent {
protected:
    N member;
public:
    Parent(N aa){
        member = aa;
    }
};


class Child1: public Parent<int>{
    public:
        Child1(int a): Parent<int>(a) {
            member += 1; // works
        }
};

template<class Q>
class Child2: public Parent<Q>{
    public:
        Child2(int a): Parent<Q>(a) {
            member += 1; // does not work (use of undeclared identifier)
        }
};

How can I use "member" in the Child2 class?

Thanks for your time

You need to use this->member or Parent<Q>::member .

In the second case, member is a " dependent name " because the existence of member from the base class template Parent<Q> depends on the type of class Q in the template, whereas in the first example there is no dependent type, the compiler can statically analyze that Parent<int> contains member .

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