【问题标题】:C++: Dynamic cast from one base to other base class templateC++:从一个基类到另一个基类模板的动态转换
【发布时间】:2017-12-11 22:04:24
【问题描述】:

鉴于下面的类结构,我想从struct B 中的方法调用struct C<O> 中的方法。 C<O> 遵循奇怪重复的模板模式。我想这样做而不在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 实际上是未知的。抱歉,这很关键。
  • 你没有结构 B 的模板
  • @JakeFreeman,不,我不能。我不拥有那个班级。
  • 你为什么不直接覆盖 o 中的foo() 方法?

标签: c++ multiple-inheritance dynamic-cast


【解决方案1】:

如果你在 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();
}

【讨论】:

  • 是的,但如果 dynamic_cast 失败,那就是 UB 的梦幻岛。所以最好在调用 moo() 之前分两步检查演员阵容是否有效。
  • 这要求每个B 使用不同的O。
【解决方案2】:

所以我建议摆脱 CRTP 并直接从 B 转换为 C。或者至少使 C 成为非模板类​​并从中派生 CRTP。这样多个O 类就无关紧要了。

struct C
{
    virtual void moo () {}
};

struct B
{
    virtual void foo ()
    {
        auto p_c{dynamic_cast<C *>(this)};
        if(p_c)
        {
            p_c->moo();
        }
    }
};

struct O: public B, public C
{
};

int main()
{
    O o;
    o.foo();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-21
    • 2017-01-13
    • 2016-01-13
    相关资源
    最近更新 更多