【问题标题】:curiously recurring template pattern and virtual inheritance奇怪地重复出现的模板模式和虚拟继承
【发布时间】: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_castc-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


【解决方案1】:

据我所知,这些不能合并。

curiously recurring template pattern 的重点是在编译时解析调用。

正如 T.C. 指出的那样。在 cmets 中,virtual inheritance 直到运行时才能解析。

这意味着两者不混合,一个必须给予。

【讨论】:

  • P.S.如果有人遇到过类似的问题,我最终将钻石替换为 C++ mixins
  • 虚拟继承在运行时解决。
猜你喜欢
  • 1970-01-01
  • 2012-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多