为什么我需要比较运算符在boost python矢量索引套件? [英] why do I need comparison operators in boost python vector indexing suite?
问题描述
我想用
std::vector<A>
到python。我的
class A{};
未实施比较运算符。当我尝试
does not have a comparison operator implemented. When I try
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的定义改为
I get an error about comparison operators. If I change the definition of A to
class A {
public:
bool operator==(const A& other) {return false;}
bool operator!=(const A& other) {return true;}
};
它像一个魅力。
为什么需要实现这些比较运算符?有没有办法使用 vector_indexing_suite
没有它们?
Why do I need to implement these comparison operators? Is there any way to use the vector_indexing_suite
without them?
推荐答案
code> vector_indexing_suite 实现一个 __包含__
成员函数,它需要存在相等运算符。因此,您的类型必须提供此类运算符。
vector_indexing_suite
implements a __contains__
member function, which requires the presence of an equality operator. As a consequence, your type must provide such an operator.
Boost.Python的沙箱版本通过使用traits来确定容器上可用的操作类型来解决此问题。例如, find
将仅在值相等时可用。
The sandbox version of Boost.Python solve this issue by using traits to determine what kind of operations are available on containers. For instance, find
will only be provided if the values are equality comparable.
默认情况下,Boost.Python考虑所有的价值观都是可比的,而不是可比的。由于您的类型不符合这些要求,您需要专门设置traits以指定它支持哪些操作:
By default, Boost.Python consider all values to be equality comparable and less-than comparable. Since your type does not meet these requirements, you need to specialize the traits to specify what operations it supports:
namespace indexing {
template<>
struct value_traits<A> : public value_traits<int>
{
static bool const equality_comparable = false;
static bool const lessthan_comparable = false;
};
}
这是记录在此处。
这篇关于为什么我需要比较运算符在boost python矢量索引套件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!