c++ - 奇怪的重复模板模式和虚拟继承

标签 c++ templates inheritance crtp static-polymorphism

我正在使用curiously recurring template pattern to model static polymorphism .

这绝对没问题,直到引入虚拟继承(以解决菱形继承(钻石问题))。

然后编译器(Visual Studio 2013)开始提示

错误 C2635:无法将“Base*”转换为“Derived*”;隐含从虚拟基类的转换

基本上,这个转换是 not allowed .

这是为什么呢? static_castc 风格转换 均失败。

是否有一种不需放弃其中之一的解决方案?

编辑:

这里是一个示例(删除虚拟并且它可以工作):

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/

相关文章:

c++ - 具有政策的 Alexandrescu 单例

C++ 正则表达式 : Get index of the Capture Group the SubMatch matched to

c++ - 按返回类型重载模板

c++ - 访问由 std::shared_ptr 包装的类的运算符重载

c++ - 类型转换 - C++

c++ - 如何从 AVI 视频中提取帧

c++ - 使用 SetUnhandledExceptionFilter 捕获 OpenMP 异常

c++ - 类模板显式特化也可以声明其他东西吗?

c++ - 模板函数名作为模板参数?

c++ - 纯虚拟的备用参数列表不会继承(需要 "using")