c++ template inheritance scheme

2019-07-18 11:35发布

问题:

I wonder if the way I code this is correct. Can I create a template claas that inherits from a template class ? If I can, is the following code correct :

template<typename Type>
class A{
    public:
        A(){};
        method_A(){//do whatever}
    protected:
        int a;
}

the second class is :

template<typename Type>
class B:public<Type> A {
    public:
        B(){};
        method_B(){this->a=0; this->method_A();}
    protected:
        int b;
}

and my last class is :

class C:public<double> B{
    public:
        C(){};
        method_C(){ b = 0; method_B();}
    protected:
        int c;
}

Why are the this-> mandatory in the class B but not in the class C ? And in general, should I always add this-> to reference arguments or methods that belong to the same class ?

回答1:

This is specifically addressed in section 14.6.2p3 of the C++03 and C++11 standards:

In the definition of a class template or a member of a class template, if a base class of the class template depends on a template parameter, the base class scope is not examined during unqualified name lookup either at the point of definition of the class template or member or during an instantiation of the class template or member.