好的,所以我正在采用一种修改过的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
]
现在我知道,通过在类B中添加
friend class A;
可以轻松解决此问题,但这并不是很简洁。还有其他方法吗?编辑:示例用法:
B b;
b.foo<B>(&b);
编辑 #2:我注意到成员函数
foo
是静态的并不重要。
A::foo
试图调用B::bar
,但由于其受保护,失败了。friend class A
听起来是正确的解决方案。 - Mark Ransom