好吧,我正在接受一种修改过的 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/