C++模板参数作为基类

exc*_*bur 2 c++ templates

为什么派生类在被模板化时不被允许访问其受保护的基类成员?

class MyBase {
protected:
    int foo;
};

template<typename Impl>
class Derived : public Impl {
public:
    int getfoo() {
            return static_cast<Impl*>(this)->foo;
    }
};
Run Code Online (Sandbox Code Playgroud)

编译器抱怨foo受到保护.为什么?

error: int MyBase::foo is protected
Run Code Online (Sandbox Code Playgroud)

Rob*_*obᵩ 11

foo通过MyBase*而不是a 访问Derived<MyBase>*.您只能通过自己的类型访问受保护的成员,而不能通过基本类型访问.

试试这个:

int getfoo() {
        return this->foo;
}
Run Code Online (Sandbox Code Playgroud)

从C++ 2003标准,11.5/1 [class.protected]:"当派生类的朋友或成员函数引用受保护的非静态成员函数或受保护的基类的非静态数据成员时...访问必须通过指向,引用,或派生类本身的对象(或从该类派生的任何类)"