Boost.Python中的向下广播

Downcast in Boost.Python

本文关键字:广播 Python Boost      更新时间:2023-10-16

EDIT:将"upcast"更正为"downstast"。

当我使用的类来自C++时,我正试图找出在Python中进行下转换的最佳方法。如果我在C++中定义了两个类:

struct Base
{
    int foo()
    {
        return 7;
    }
};
struct Derived : Base
{
    int bar()
    {
        return 42;
    }
};

和另一个功能

Base baz()
{
    return Derived();
}

如果我尝试Python

der = baz()
print der.foo()
print der.bar()

对bar()的调用失败,因为Python只知道Base中的函数。

我的解决方案是在Derived:中添加另一个函数

Derived * fromBase(Base * b)
{
    return reinterpret_cast<Derived *>(b);
}

如果我随后将Python脚本的第一行更改为der = Derived.fromBase(baz()),那么该脚本将按预期工作。

然而,我使用repret_cast来完成这项工作的事实似乎是非常错误的。有没有一种更好的方式来进行向下转换,而不需要使用像interpret_cast这样危险的东西?如果没有,fromBase()的退货政策应该是什么?

在有人问之前,是的,沮丧是必要的。这就是我必须使用的图书馆的工作方式。

编辑:

我正在寻找像这样的C#代码工作的东西:

Base b = new Derived();
Derived d = b as Derived;
if (d != null)
    ...
Base baz()
{
    return Derived();
}

从返回类型可以看出,这返回一个Base对象,而不是一个Derived对象。所以没有什么可以向下转换(而不是向上转换)的。所以你首先需要解决这个问题。

更重要的是,你是对的,reinterpret_cast在这种情况下肯定是阴暗的。dynamic_cast实际上是用于下变频的工具。

更重要的是,你应该问问自己,为什么你觉得有必要沮丧。您的示例代码可能是合成的,不能代表您的确切问题,但为什么baz不应该返回Derived呢?


以下是您的代码片段:

Derived d;
Base& b = d;
if(Base* p = dynamic_cast<Derived*>(&b))
    // okay; b is actually an instance of Derived