c++ - 从模板化(静态)成员函数访问 protected 成员

标签 c++ templates

好吧,我正在接受一种修改过的 CRTP在这里路由以避免虚函数查找。但我就是无法理解它给我的一个错误...

所以我正在尝试翻译:

class A
{
public:
    static void foo(A *pA)
    {
        pA->bar();
    }

protected:
    virtual void bar()
    {
        TRACE0(_T("A::bar\n"));
    }
};

class B : public A
{
protected:
    virtual void bar()
    {
        TRACE0(_T("B::bar\n"));
    }
};

按预期工作:

class A
{
public:
    template <class T>
    static void foo(T *pT)
    {
        pT->bar();
    }

protected:
    void bar()
    {
        TRACE0(_T("A::bar\n"));
    }
};

class B : public A
{
protected:
    void bar()
    {
        TRACE0(_T("B::bar\n"));
    }
};

给出了错误:

error C2248: 'B::bar' : cannot access protected member declared in class 'B'
see declaration of 'B::bar'
see declaration of 'B'
see reference to function template instantiation 'void A::foo<B>(T *)' 
being compiled with
[
    T=B
]

现在我知道,通过将 friend class A; 添加到 B 类可以很容易地解决这个问题,但这不是很简洁。没有别的办法吗?

编辑:用法示例:

B b;
b.foo<B>(&b);

编辑#2:我注意到成员函数 foo 是静态的并不重要。

最佳答案

在第一种情况下,bar 是虚函数,foo 通过指向 A 的指针访问它,从而调用函数指针和指定的索引由类 A 布局的 Vtable。因此它有效。

但是,在第二种情况下,A::foo 显式地从它无权访问的不同类中调用非虚函数。 B::bar 不是 A::bar 的虚拟重载 - 它是完全不同的无关函数。

因此,恐怕让 friend class A; 是你能得到的最巧妙的方法。

关于c++ - 从模板化(静态)成员函数访问 protected 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9039570/

相关文章:

c++ - opencv2.4.13 中的 Min, Max, Avg 过滤器

C++函数模板问题

c++ - 这个 for 循环可以用预处理器完成吗?

django - 如何检查是否在django模板中选中了复选框

c++ - MFC中的窗口消息管理:是否必须添加基类调用?

c++ - 初始化类的 std::array 类型的继承成员 var 的最佳方法?

c++ - 按位运算的性能下降

C++ : Fast searching in 2d array

c++ - 为什么函数模板不能访问前向声明的类型?

c++ - 如何创建没有类型名称的迭代器?