]> git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/python/doc/reference/implicit.qbk
add subtree-ish sources for 12.0.3
[ceph.git] / ceph / src / boost / libs / python / doc / reference / implicit.qbk
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
28 using namespace boost::python;
29
30 struct X
31 {
32 X(int x) : v(x) {}
33 operator int() const { return v; }
34 int v;
35 };
36
37 int x_value(X const& x)
38 {
39 return x.v;
40 }
41
42 X make_x(int n) { return X(n); }
43
44 BOOST_PYTHON_MODULE(implicit_ext)
45 {
46 def("x_value", x_value);
47 def("make_x", make_x);
48
49 class_<X>("X",
50 init<int>())
51 ;
52
53 implicitly_convertible<X,int>();
54 implicitly_convertible<int,X>();
55 }
56 ``
57 In Python:
58 ``
59 >>> from implicit_ext import *
60 >>> x_value(X(42))
61 42
62 >>> x_value(42)
63 42
64 >>> x = make_x(X(42))
65 >>> x_value(x)
66 42
67 ``
68 [endsect]
69 [endsect]