编辑:将“upcast”更正为“downcast”。
当我使用的类来自 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())
,脚本将按预期工作。
但是,我使用 reinterpret_cast 来完成这项工作这一事实似乎是非常错误的。有没有更好的向下转换方法,不需要使用像 reinterpret_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
关于c++ - 在 Boost.Python 中沮丧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12222824/