C++ 模板参数作为基类

标签 c++ templates

为什么派生类在模板化时没有权限访问其 protected 基类成员?

class MyBase {
protected:
    int foo;
};

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

编译器提示 foo 受到保护。为什么?

error: int MyBase::foo is protected

最佳答案

您正在访问 foo通过 MyBase*而不是 Derived<MyBase>* .您只能通过您自己的类型访问 protected 成员,而不能通过基类型访问。

试试这个:

int getfoo() {
        return this->foo;
}

来自 C++ 2003 标准,11.5/1 [class.protected] :“当派生类的友元或成员函数引用 protected 非静态成员函数或 基类的 protected 非静态数据成员……访问必须通过 派生类本身(或从该类派生的任何类)的指针、引用或对象”

关于C++ 模板参数作为基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10095542/

相关文章:

Jinja2 中的 Python lambda

c++ - 模板类的方法取决于模板参数

c++ - 如何用模板类型初始化成员变量数组?

c++ - Xcode 对 lambda 函数的支持

c++ - 将glm四元数转换为旋转矩阵并将其与opengl一起使用

c++ - 使用可变参数模板指定友元类

visual-studio - Visual Studio 2008:如何安装项目模板

c++ - 在这种情况下我应该避免使用 "goto"吗?

c++ - 枚举和使用 wmp 可视化工具

c++ - 在不使用其他变量的情况下用 C++ 编写程序集