鉴于下面的类结构,我想调用 struct C<O>
中的方法来自 struct B
中的方法. C<O>
follows 遵循奇怪的重复模板模式。我想在不将方法放在 struct O
中的情况下执行此操作.在 struct O
中放置方法会破坏 struct C<>
的目的.我怀疑这是不可能的,但我想我会问。
编辑: struct O
可以是同时具有 struct B
的一组类型中的任何一种。和 struct C<O>
作为基类。
struct B
{
virtual void foo ()
{
// dynamic_cast this to C<O>* and call C<O>::moo()
}
};
template <typename P>
struct C
{
virtual void moo () { }
};
struct O :
public B,
public C<O>
{
};
最佳答案
如果您按照 O 的定义外联地定义 foo,它工作正常:
struct B
{
virtual void foo();
};
template <typename P>
struct C
{
virtual void moo() {}
};
struct O :
public B,
public C<O>
{
};
void B::foo()
{
dynamic_cast<C<O>*>(this)->moo();
}
关于C++:从一个基类模板到另一个基类模板的动态转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47762217/