implicit.qbk 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. [section boost/python/implicit.hpp]
  2. [section Introduction]
  3. `implicitly_convertible` allows Boost.Python to implicitly take advantage of a C++ implicit or explicit conversion when matching Python objects to C++ argument types.
  4. [endsect]
  5. [section Function template `implicit_convertible`]
  6. ``
  7. template <class Source, class Target>
  8. void implicitly_convertible();
  9. ``
  10. [table
  11. [[Parameter][Description]]
  12. [[Source][The source type of the implicit conversion]]
  13. [[Target][The target type of the implicit conversion]]
  14. ]
  15. [variablelist
  16. [[Requires][The declaration `Target t(s);`, where s is of type Source, is valid.]]
  17. [[Effects][registers an rvalue `from_python` converter to Target which can succeed for any `PyObject* p` iff there exists any registered converter which can produce Source rvalues]]
  18. [[Rationale][C++ users expect to be able to take advantage of the same sort of interoperability in Python as they do in C++.]]
  19. ]
  20. [endsect]
  21. [section Example]
  22. In C++:
  23. ``
  24. #include <boost/python/class.hpp>
  25. #include <boost/python/implicit.hpp>
  26. #include <boost/python/module.hpp>
  27. using namespace boost::python;
  28. struct X
  29. {
  30. X(int x) : v(x) {}
  31. operator int() const { return v; }
  32. int v;
  33. };
  34. int x_value(X const& x)
  35. {
  36. return x.v;
  37. }
  38. X make_x(int n) { return X(n); }
  39. BOOST_PYTHON_MODULE(implicit_ext)
  40. {
  41. def("x_value", x_value);
  42. def("make_x", make_x);
  43. class_<X>("X",
  44. init<int>())
  45. ;
  46. implicitly_convertible<X,int>();
  47. implicitly_convertible<int,X>();
  48. }
  49. ``
  50. In Python:
  51. ``
  52. >>> from implicit_ext import *
  53. >>> x_value(X(42))
  54. 42
  55. >>> x_value(42)
  56. 42
  57. >>> x = make_x(X(42))
  58. >>> x_value(x)
  59. 42
  60. ``
  61. [endsect]
  62. [endsect]