proxy.hpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Copyright David Abrahams 2002.
  2. // Distributed under the Boost Software License, Version 1.0. (See
  3. // accompanying file LICENSE_1_0.txt or copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. #ifndef PROXY_DWA2002615_HPP
  6. # define PROXY_DWA2002615_HPP
  7. # include <boost/python/detail/prefix.hpp>
  8. # include <boost/python/object_core.hpp>
  9. # include <boost/python/object_operators.hpp>
  10. namespace boost { namespace python { namespace api {
  11. template <class Policies>
  12. class proxy : public object_operators<proxy<Policies> >
  13. {
  14. typedef typename Policies::key_type key_type;
  15. typedef proxy const& assignment_self;
  16. public:
  17. proxy(object const& target, key_type const& key);
  18. operator object() const;
  19. // to support a[b] = c[d]
  20. proxy const& operator=(assignment_self) const;
  21. template <class T>
  22. inline proxy const& operator=(T const& rhs) const
  23. {
  24. Policies::set(m_target, m_key, object(rhs));
  25. return *this;
  26. }
  27. public: // implementation detail
  28. void del() const;
  29. private:
  30. object m_target;
  31. key_type m_key;
  32. };
  33. template <class T>
  34. inline void del(proxy<T> const& x)
  35. {
  36. x.del();
  37. }
  38. //
  39. // implementation
  40. //
  41. template <class Policies>
  42. inline proxy<Policies>::proxy(object const& target, key_type const& key)
  43. : m_target(target), m_key(key)
  44. {}
  45. template <class Policies>
  46. inline proxy<Policies>::operator object() const
  47. {
  48. return Policies::get(m_target, m_key);
  49. }
  50. // to support a[b] = c[d]
  51. template <class Policies>
  52. inline proxy<Policies> const& proxy<Policies>::operator=(typename proxy::assignment_self rhs) const
  53. {
  54. return *this = python::object(rhs);
  55. }
  56. # define BOOST_PYTHON_PROXY_INPLACE(op) \
  57. template <class Policies, class R> \
  58. proxy<Policies> const& operator op(proxy<Policies> const& lhs, R const& rhs) \
  59. { \
  60. object old(lhs); \
  61. return lhs = (old op rhs); \
  62. }
  63. BOOST_PYTHON_PROXY_INPLACE(+=)
  64. BOOST_PYTHON_PROXY_INPLACE(-=)
  65. BOOST_PYTHON_PROXY_INPLACE(*=)
  66. BOOST_PYTHON_PROXY_INPLACE(/=)
  67. BOOST_PYTHON_PROXY_INPLACE(%=)
  68. BOOST_PYTHON_PROXY_INPLACE(<<=)
  69. BOOST_PYTHON_PROXY_INPLACE(>>=)
  70. BOOST_PYTHON_PROXY_INPLACE(&=)
  71. BOOST_PYTHON_PROXY_INPLACE(^=)
  72. BOOST_PYTHON_PROXY_INPLACE(|=)
  73. # undef BOOST_PYTHON_PROXY_INPLACE
  74. template <class Policies>
  75. inline void proxy<Policies>::del() const
  76. {
  77. Policies::del(m_target, m_key);
  78. }
  79. }}} // namespace boost::python::api
  80. #endif // PROXY_DWA2002615_HPP