我想用
公开 C++ 代码std::vector<A>
到 python 。我的
class A{};
没有实现比较运算符。当我尝试
BOOST_PYTHON_MODULE(libmyvec)
{
using namespace boost::python;
class_<A>("A");
class_<std::vector<A> >("Avec")
.def(boost::python::vector_indexing_suite<std::vector<A> >());
}
我收到有关比较运算符的错误。如果我将 A 的定义更改为
class A {
public:
bool operator==(const A& other) {return false;}
bool operator!=(const A& other) {return true;}
};
它就像一个魅力。
为什么我需要实现这些比较运算符?有没有办法在没有它们的情况下使用 vector_indexing_suite
?
最佳答案
vector_indexing_suite
实现了一个 __contains__
成员函数,它需要一个相等运算符。因此,您的类型必须提供这样的运算符。
Boost.Python 的沙盒版本通过使用特征来确定容器上可用的操作类型来解决这个问题。例如,find
仅在值相等且可比较时才会提供。
默认情况下,Boost.Python 将所有值视为相等可比较和小于可比较。由于您的类型不满足这些要求,您需要专门化特征以指定它支持哪些操作:
namespace indexing {
template<>
struct value_traits<A> : public value_traits<int>
{
static bool const equality_comparable = false;
static bool const lessthan_comparable = false;
};
}
这已记录在案 here .
关于c++ - 为什么在 boost python vector 索引套件中需要比较运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10680691/