[英]Using Boost Python, I can wrap C++ overloaded operators “+=”, “-=”, “*=”, but not “/=”?
Boost Python 有一个非常简单的包装重载运算符的方法。 The tutorial for exposing C++ classes, methods, etc. at boost.org ( https://www.boost.org/doc/libs/1_66_0/libs/python/doc/html/tutorial/tutorial/exposing.html ) gives this例子:
重载的 C++ 运算符,例如 class,FilePos:
class FilePos { /*...*/ };
FilePos operator+(FilePos, int);
FilePos operator+(int, FilePos);
int operator-(FilePos, FilePos);
FilePos operator-(FilePos, int);
FilePos& operator+=(FilePos&, int);
FilePos& operator-=(FilePos&, int);
bool operator<(FilePos, FilePos);
如何将 map 转换为 Python:
class_<FilePos>("FilePos")
.def(self + int()) // __add__
.def(int() + self) // __radd__
.def(self - self) // __sub__
.def(self - int()) // __sub__
.def(self += int()) // __iadd__
.def(self -= other<int>())
.def(self < self); // __lt__
我有一个名为“Angle”的 C++ class 代表一个角度。 它具有重载的运算符,包括“+=”、“-=”、“*=”和“/=”。 每个重载运算符都设计为将某些 double 类型的输入与角度 class 保持的度值相加、减、乘或除。 Angle class 包装器以与上面示例中描述的完全相同的方式映射这些重载运算符。 当我在 Python 中测试加法、减法和乘法运算符时,它们工作得非常好。 除法运算符,并非如此。 当我像这样运行一个简单的测试时:
A = Angle(1) # instantiate Angle object with magnitude of 1 radian
A /= 2.0 # attempt to divide the radian measurement by 2
我收到以下错误:
TypeError: unsupported operand type(s) for /=: 'Angle' and 'float'
基于这个问题:
我看到 Python3(我正在使用的版本)有一种独特的方式来理解“/”字符。 但是,此解决方案对我不起作用,因为我使用的 class 是包装的 C++ class。
My question: is there a way to map the overloaded operator "/=" from C++ to python using boost in such a way that retains the same syntax (ie not writing a thin wrapper in C++ called "selfdiv" that performs the same operation,但必须用“Angle.selfdiv()”调用)? 也许某种方式可以覆盖 Python 如何解释该正斜杠字符?
Python 3 改变了除法运算符的定义方式,Boost.Python 的自动生成版本使用旧的 Python 2 样式进行就地除法,不再有效。 这似乎是一个疏忽,因为非就地版本已更新为 Python 3 的__truediv__
魔术方法。 关于这件事有一个开放的 GitHub 问题。 在它得到修复之前,您可以像定义任何其他 class 成员 function 一样定义__itruediv__
和/或__ifloordiv__
:
class_<Foo>("Foo")
.def(
"__itruediv__",
&Foo::operator/=,
return_self<>{}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.