我正在使用curiously recurring template pattern to model static polymorphism .
这绝对没问题,直到引入虚拟继承
(以解决菱形继承(钻石问题)
)。
然后编译器(Visual Studio 2013)开始提示
错误 C2635:无法将“Base*”转换为“Derived*”;隐含从虚拟基类的转换
基本上,这个转换是 not allowed .
这是为什么呢? static_cast
和 c 风格转换
均失败。
是否有一种不需放弃其中之一的解决方案?
编辑:
这里是一个示例(删除虚拟并且它可以工作):
template <class Derived>
struct Base
{
void interface()
{
static_cast<Derived*>(this)->implementation();
}
};
struct Derived : virtual Base<Derived>
{
void implementation() { std::cout << "hello"; }
};
int main()
{
Derived d;
d.interface();
}
最佳答案
据我所知,这些不能合并。
奇怪的重复模板模式
的要点是在编译时解析调用。
正如 T.C. 所指出的那样注释中,虚拟继承
只有在运行时才能解决。
这意味着两者不能混合,一个必须给予。
关于c++ - 奇怪的重复模板模式和虚拟继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23953995/