【发布时间】:2014-05-30 11:54:21
【问题描述】:
我正在使用curiously recurring template pattern to model static polymorphism。
这绝对没问题,直到有人介绍virtual inheritance(以解决diamond problem)。
然后编译器(Visual Studio 2013)开始抱怨
error C2635: cannot convert a 'Base*' to a 'Derived*'; conversion from a virtual base class is implied
基本上,这个转换是not allowed。
这是为什么呢? static_cast 和 c-style cast 都失败了。
有没有不放弃其中一个的解决方案?
编辑:
这里是一个示例(删除虚拟,它可以工作):
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();
}
【问题讨论】:
-
可能是您遇到了 XY 问题。您应该详细说明为什么需要它是虚拟的。
-
这个例子可能过于简单了,但为什么不直接使用私有虚函数,即模板方法模式呢?
标签: c++ templates inheritance crtp static-polymorphism