Карта сайта Kansoftware
НОВОСТИУСЛУГИРЕШЕНИЯКОНТАКТЫ
Разработка программного обеспечения

boost/python/operators.hpp

Boost , Boost.Python Reference Manual , Chapter 2. High Level Components

Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

PrevUpHomeNext

предоставляет типы и функции для автоматического генерирования Pythonспециальными методамииз соответствующих конструкций C++. Большинство этих конструкций являются операторными выражениями, отсюда и название. Чтобы использовать объект, замените объектselfна объект типа класса, завернутый в выражение, которое будет выставлено, и передайте результатclass_<>::def(). Большая часть того, что раскрыто в этом заголовке, должна рассматриваться как часть реализации, поэтому здесь подробно не документируется.

<self_ns::self_t>является фактическим типомсамобъект. Библиотека изолирует<self_t>в своем собственном пространстве имен<self_ns>, чтобы предотвратить обнаружение обобщенных шаблонов операторов, которые работают на ней, путем поиска в других контекстах. Это следует рассматривать как деталь реализации, поскольку пользователи никогда не должны упоминать<self_t>напрямую.

namespace boost { namespace python { namespace self_ns {
{
   unspecified-type-declaration self_t;
   // inplace operators
   template <class T> operator_<unspecified> operator+=(self_t, T);
   template <class T> operator_<unspecified> operator-=(self_t, T);
   template <class T> operator_<unspecified> operator*=(self_t, T);
   template <class T> operator_<unspecified> operator/=(self_t, T);
   template <class T> operator_<unspecified> operator%=(self_t, T);
   template <class T> operator_<unspecified> operator>>=(self_t, T);
   template <class T> operator_<unspecified> operator<<=(self_t, T);
   template <class T> operator_<unspecified> operator&=(self_t, T);
   template <class T> operator_<unspecified> operator^=(self_t, T);
   template <class T> operator_<unspecified> operator|=(self_t, T);
   // comparisons
   template <class L, class R> operator_<unspecified> operator==(L const&, R const&);
   template <class L, class R> operator_<unspecified> operator!=(L const&, R const&);
   template <class L, class R> operator_<unspecified> operator<(L const&, R const&);
   template <class L, class R> operator_<unspecified> operator>(L const&, R const&);
   template <class L, class R> operator_<unspecified> operator<=(L const&, R const&);
   template <class L, class R> operator_<unspecified> operator>=(L const&, R const&);
   // non-member operations
   template <class L, class R> operator_<unspecified> operator+(L const&, R const&);
   template <class L, class R> operator_<unspecified> operator-(L const&, R const&);
   template <class L, class R> operator_<unspecified> operator*(L const&, R const&);
   template <class L, class R> operator_<unspecified> operator/(L const&, R const&);
   template <class L, class R> operator_<unspecified> operator%(L const&, R const&);
   template <class L, class R> operator_<unspecified> operator>>(L const&, R const&);
   template <class L, class R> operator_<unspecified> operator<<(L const&, R const&);
   template <class L, class R> operator_<unspecified> operator&(L const&, R const&);
   template <class L, class R> operator_<unspecified> operator^(L const&, R const&);
   template <class L, class R> operator_<unspecified> operator|(L const&, R const&);
   template <class L, class R> operator_<unspecified> pow(L const&, R const&);
   // unary operations
   operator_<unspecified> operator-(self_t);
   operator_<unspecified> operator+(self_t);
   operator_<unspecified> operator~(self_t);
   operator_<unspecified> operator!(self_t);
   // value operations
   operator_<unspecified> int_(self_t);
   operator_<unspecified> long_(self_t);
   operator_<unspecified> float_(self_t);
   operator_<unspecified> complex_(self_t);
   operator_<unspecified> str(self_t);
   operator_<unspecified> repr(self_t);
}}};

Приведенные ниже таблицы описывают методы, полученные, когда результаты описанных выражений передаются в качестве аргументовclass_<>::def().<x>является объектом типа класса, завернутого в обертку.

В таблице ниже, если<r>является объектом типадругой,<y>является объектом типа<T>; в противном случае<y>является объектом того же типа, что и<r>.

C++ выражение

Метод Python называется

C++ Осуществление

<self+= r>

<__iadd__>

<x+= y>

<self-= r>

<__isub__>

<x-= y>

<self*= r>

<__imul__>

<x*= y>

<self/= r>

<__idiv__>

<x/= y>

<self%= r>

<__imod__>

<x%= y>

<self>>= r>

<__irshift__>

<x>>= y>

<self<<= r>

<__ilshift__>

<x<<= y>

<self&= r>

<__iand__>

<x&= y>

<self^= r>

<__ixor__>

<x^= y>

<self|= r>

<__ior__>

<x|= y>

В таблицах ниже, если<r>имеет типself_t,<y>является объектом того же типа, что и<x>; если<l>или<r>является объектом типадругой,<y>является объектом типа<T>; в противном случае<y>является объектом того же типа, что и<l>или<r>.<l>никогда не является объектом типаself_t.

Колонка экспрессий Python иллюстрирует выражения, которые будут поддерживаться в Python для объектов, конвертируемых в типы x и y. Вторичная операция возникает из-за правил отражения Pythonдля богатых операторов сравнения и используется только тогда, когда соответствующая операция не определена как метод объекта y.

C++ выражение

Метод Python называется

C++ Осуществление

Python Expression (первичная, вторичная)

<self== r>

<__eq__>

<x== y>

<x== y>,<y== x>

<l== self>

<__eq__>

<y== x>

<y== x>,<x== y>

<self!= r>

<__nq__>

<x!= y>

<x!= y>,<y!= x>

<l!= self>

<__nq__>

<y!= x>

<y!= x>,<x!= y>

<self< r>

<__lt__>

<x< y>

<x< y>,<y> x>

<l< self>

<__gt__>

<y< x>

<y> x>,<x< y>

<self> r>

<__gt__>

<x> y>

<x> y>,<y< x>

<l> self>

<__lt__>

<y> x>

<y< x>,<x> y>

<self<= r>

<__le__>

<x<= y>

<x<= y>,<y>= x>

<l<= self>

<__ge__>

<y<= x>

<y>= x>,<x<= y>

<self>= r>

<__ge__>

<x>= y>

<x>= y>,<y<= x>

<l<= self>

<__le__>

<y>= x>

<y<= x>,<x>= y>

Операции, названия которых начинаются с «__r» ниже, будут называться только в том случае, если левый операнд уже не поддерживает данную операцию, как описаноздесь.

C++ выражение

Метод Python называется

C++ Осуществление

<self+ r>

<__add__>

<x+ y>

<l+ self>

<__radd__>

<y+ x>

<self- r>

<__sub__>

<x- y>

<l- self>

<__rsub__>

<y- x>

<self* r>

<__mult__>

<x* y>

<l* self>

<__rmult__>

<y* x>

<self/ r>

<__div__>

<x/ y>

<l/ self>

<__rdiv__>

<y/ x>

<self% r>

<__mod__>

<x% y>

<l% self>

<__rmod__>

<y% x>

<self>> r>

<__rshift__>

<x>> y>

<l>> self>

<__rrshift__>

<y>> x>

<self<< r>

<__lshift__>

<x<< y>

<l<< self>

<__rlshift__>

<y<< x>

<self& r>

<__and__>

<x& y>

<l& self>

<__rand__>

<y& x>

<self^ r>

<__xor__>

<x^ y>

<l^ self>

<__rxor__>

<y^ x>

<self| r>

<__or__>

<x| y>

<l| self>

<__ror__>

<y| x>

<pow(self, r)>

<__pow__>

<x** y>

<pow(l, self)>

<__rpow__>

<y** x>

C++ выражение

Метод Python называется

C++ Осуществление

<-self>

<__neg__>

<-x>

<+self>

<__pos__>

<+x>

<~self>

<__invert__>

<~x>

<notself>или<!self>

<__nonzero__>

<!!x>

C++ выражение

Метод Python называется

C++ Осуществление

<int_(self)>

<__int__>

<long(x)>

<long_(self)>

<__long__>

<PyLong_FromLong(x)>

<float_(self)>

<__float__>

<double(x)>

<complex_(self)>

<__complex__>

<std::complex<double>(x)>

<str(self)>

<__str__>

<lexical_cast<std::string>(x)>

<repr(self)>

<__repr__>

<lexical_cast<std::string>(x)>

Случаи<other<T>>могут быть использованы в операторских выражениях ся; результат эквивалентен тому же выражению с<T>объектом вместо<other<T>>. Используйте<other<T>>для предотвращения строительства<T>объекта в случае, если он тяжеловесен, когда нет конструктора или просто для ясности.

namespace boost { namespace python
{
  template <class T>
  struct other
  {
  };
}}

Обоснования<detail::operator_<>>используются в качестве возвратного типа операторских выражений с участиемсам. Это следует рассматривать как деталь реализации и документируется здесь только как способ показать, как результат самовыражения соответствует вызовам<class_<>::def()>.

namespace boost { namespace python { namespace detail
{
  template <unspecified>
  struct operator_
  {
  };
}}}
namespace boost { namespace python
{
  using self_ns::self;
}}
#include <boost/python/module.hpp>
#include <boost/python/class.hpp>
#include <boost/python/operators.hpp>
#include <boost/operators.hpp>
struct number
   : boost::integer_arithmetic<number>
{
    explicit number(long x_) : x(x_) {}
    operator long() const { return x; }
    template <class T>
    number& operator+=(T const& rhs)
    { x += rhs; return *this; }
    template <class T>
    number& operator-=(T const& rhs)
    { x -= rhs; return *this; }
    template <class T>
    number& operator*=(T const& rhs)
    { x *= rhs; return *this; }
    template <class T>
    number& operator/=(T const& rhs)
    { x /= rhs; return *this; }
    template <class T>
    number& operator%=(T const& rhs)
    { x %= rhs; return *this; }
   long x;
};
using namespace boost::python;
BOOST_PYTHON_MODULE(demo)
{
   class_<number>("number", init<long>())
      // interoperate with self
      .def(self += self)
      .def(self + self)
      .def(self -= self)
      .def(self - self)
      .def(self *= self)
      .def(self * self)
      .def(self /= self)
      .def(self / self)
      .def(self %= self)
      .def(self % self)
      // Convert to Python int
      .def(int_(self))
      // interoperate with long
      .def(self += long())
      .def(self + long())
      .def(long() + self)
      .def(self -= long())
      .def(self - long())
      .def(long() - self)
      .def(self *= long())
      .def(self * long())
      .def(long() * self)
      .def(self /= long())
      .def(self / long())
      .def(long() / self)
      .def(self %= long())
      .def(self % long())
      .def(long() % self)
      ;
}

PrevUpHomeNext

Статья boost/python/operators.hpp раздела Boost.Python Reference Manual Chapter 2. High Level Components может быть полезна для разработчиков на c++ и boost.




Материалы статей собраны из открытых источников, владелец сайта не претендует на авторство. Там где авторство установить не удалось, материал подаётся без имени автора. В случае если Вы считаете, что Ваши права нарушены, пожалуйста, свяжитесь с владельцем сайта.



:: Главная :: Chapter 2. High Level Components ::


реклама


©KANSoftWare (разработка программного обеспечения, создание программ, создание интерактивных сайтов), 2007
Top.Mail.Ru

Время компиляции файла: 2024-08-30 11:47:00
2025-05-20 01:23:52/0.0075700283050537/0