File: class.qbk

package info (click to toggle)
boost1.83 1.83.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 545,632 kB
  • sloc: cpp: 3,857,086; xml: 125,552; ansic: 34,414; python: 25,887; asm: 5,276; sh: 4,799; ada: 1,681; makefile: 1,629; perl: 1,212; pascal: 1,139; sql: 810; yacc: 478; ruby: 102; lisp: 24; csh: 6
file content (308 lines) | stat: -rw-r--r-- 19,171 bytes parent folder | download | duplicates (10)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
[section boost/python/class.hpp]
[section Introduction]
`<boost/python/class.hpp>` defines the interface through which users expose their C++ classes to Python. It declares the `class_` class template, which is parameterized on the class type being exposed. It also exposes the `init`, `optional` and `bases` utility class templates, which are used in conjunction with `class_`.

`<boost/python/class_fwd.hpp>` contains a forward declaration of the `class_` class template.
[endsect]
[section Class template `class_<T, Bases, HeldType, NonCopyable>`]
Creates a Python class associated with the C++ type passed as its first parameter. Although it has four template parameters, only the first one is required. The three optional arguments can actually be supplied *in any order*\ ; Boost.Python determines the role of the argument from its type.
[table
 [[Template Parameter][Requirements][Semantics][Default]]
 [[`T`][A class type.][The class being wrapped][]]
 [[Bases]
  [A specialization of [link high_level_components.boost_python_class_hpp.class_template_bases_t1_t2_tn bases<...>] which specifies previously-exposed C++ base classes of `T`.]
  [Registers `from_python` conversions from wrapped `T` instances to each of its exposed direct and indirect bases. For each polymorphic base `B`, registers conversions from indirectly-held wrapped `B` instances to `T`.][[link high_level_components.boost_python_class_hpp.class_template_bases_t1_t2_tn bases<>]]]
  [[HeldType][Must be `T`, a class derived from `T`, or a [link concepts.dereferenceable.concept_requirements Dereferenceable] type for which `pointee<HeldType>::type` is `T` or a class derived from `T`.][Specifies the type that is actually embedded in a Python object wrapping a `T` instance when `T`\ 's constructor is called or when a `T` or `T*` is converted to Python without the use of [link function_invocation_and_creation.boost_python_ptr_hpp.functions ptr], `ref`, or [link concepts.callpolicies Call Policies] such as [link function_invocation_and_creation.models_of_callpolicies.boost_python_return_internal_ref.class_template_return_internal_r return_internal_reference]. More details below.][`T`]]
  [[NonCopyable][If supplied, must be `boost::noncopyable`.][Suppresses automatic registration of `to_python` conversions which copy `T` instances. Required when `T` has no publicly-accessible copy constructor.][An unspecified type other than boost::noncopyable.]]
]
[section HeldType Semantics]

# If HeldType is derived from `T`, its exposed constructor(s) must accept an initial `PyObject*` argument which refers back to the Python object that contains the HeldType instance, as shown in this example. This argument is not included in the [link high_level_components.boost_python_init_hpp.introduction.init_expressions init-expression] passed to [link high_level_components.boost_python_class_hpp.class_template_class_t_bases_hel.class_template_class_modifier_fu def(init_expr)], below, nor is it passed explicitly by users when Python instances of `T` are created. This idiom allows C++ virtual functions which will be overridden in Python to access the Python object so the Python method can be invoked. Boost.Python automatically registers additional converters which allow wrapped instances of `T` to be passed to wrapped C++ functions expecting HeldType arguments.
# Because Boost.Python will always allow wrapped instances of `T` to be passed in place of HeldType arguments, specifying a smart pointer for HeldType allows users to pass Python `T` instances where a smart pointer-to-T is expected. Smart pointers such as `std::auto_ptr<>` or `boost::shared_ptr<>` which contain a nested type `element_type` designating the referent type are automatically supported; additional smart pointer types can be supported by specializing `pointee<HeldType>`.
# As in case 1 above, when HeldType is a smart pointer to a class derived from `T`, the initial `PyObject*` argument must be supplied by all of HeldType's exposed constructors.
# Except in cases 1 and 3, users may optionally specify that T itself gets initialized with a similar initial `PyObject*` argument by specializing [link utility_and_infrastructure.boost_python_has_back_reference_.class_template_has_back_referenc has_back_reference<T>].

[endsect]
[section Class template `class_` synopsis]
``
  namespace boost { namespace python
  {
  template <class T
      , class Bases = bases<>
            , class HeldType = T
            , class NonCopyable = unspecified
           >
  class class_ : public object
  {
    // Constructors with default __init__
    class_(char const* name);
    class_(char const* name, char const* docstring);

    // Constructors, specifying non-default __init__
    template <class Init>
    class_(char const* name, Init);
    template <class Init>
    class_(char const* name, char const* docstring, Init);

    // Exposing additional __init__ functions
    template <class Init>
    class_& def(Init);

    // defining methods
    template <class F>
    class_& def(char const* name, F f);
    template <class Fn, class A1>
    class_& def(char const* name, Fn fn, A1 const&);
    template <class Fn, class A1, class A2>
    class_& def(char const* name, Fn fn, A1 const&, A2 const&);
    template <class Fn, class A1, class A2, class A3>
    class_& def(char const* name, Fn fn, A1 const&, A2 const&, A3 const&);

    // declaring method as static
    class_& staticmethod(char const* name);
    
    // exposing operators
    template <unspecified>
    class_& def(detail::operator_<unspecified>);

    // Raw attribute modification
    template <class U>
    class_& setattr(char const* name, U const&);

    // exposing data members
    template <class D>
    class_& def_readonly(char const* name, D T::*pm);

    template <class D>
    class_& def_readwrite(char const* name, D T::*pm);

    // exposing static data members
    template <class D>
    class_& def_readonly(char const* name, D const& d);
    template <class D>
    class_& def_readwrite(char const* name, D& d);

    // property creation
    template <class Get>
    void add_property(char const* name, Get const& fget, char const* doc=0);
    template <class Get, class Set>
    void add_property(
        char const* name, Get const& fget, Set const& fset, char const* doc=0);

    template <class Get>
    void add_static_property(char const* name, Get const& fget);
    template <class Get, class Set>
    void add_static_property(char const* name, Get const& fget, Set const& fset);

    // pickle support
    template <typename PickleSuite>
    self& def_pickle(PickleSuite const&);
    self& enable_pickling();
  };
  }}
``
[endsect]
[section Class template `class_` constructors]
``
  class_(char const* name);
  class_(char const* name, char const* docstring);
  template <class Init>
  class_(char const* name, Init init_spec);
  template <class Init>
  class_(char const* name, char const* docstring, Init init_spec);
``

[variablelist
 [[Requires][name is an [link ntbs] which conforms to Python's [@http://www.python.org/doc/current/ref/identifiers.html identifier naming rules]. If docstring is supplied, it must be an [link ntbs]. If `init_spec` is supplied, it must be either the special enumeration constant `no_init` or an [link high_level_components.boost_python_init_hpp.introduction.init_expressions init-expression] compatible with `T`.]]
 [[Effects][Constructs a `class_` object holding a Boost.Python extension class named name. The named attribute of the [link high_level_components.boost_python_scope_hpp.introduction current scope] is bound to the new extension class.

* If supplied, the value of docstring is bound to the `__doc__` attribute of the extension class.
* If `init_spec` is `no_init`, a special `__init__` function is generated which always raises a Python exception. Otherwise, `this->def(init_spec)` is called.
* If `init_spec` is not supplied, `this->def(init<>())` is called.]]
 [[Rationale][Allowing the user to specify constructor arguments in the `class_<>` constructor helps her to avoid the common run-time errors which result from invoking wrapped member functions without having exposed an `__init__` function which creates the requisite `T` instance. Types which are not default-constructible will cause a compile-time error unless `Init` is supplied. The user must always supply name as there is currently no portable method to derive the text of the class name from its type.]]
]
[endsect]
[section Class template `class_` modifier functions]
``
  template <class Init>
  class_& def(Init init_expr);
``

[variablelist
 [[Requires][`init_expr` is the result of an [link high_level_components.boost_python_init_hpp.introduction.init_expressions init-expression] compatible with `T`.]]
 [[Effects][For each [link high_level_components.boost_python_init_hpp.introduction.init_expressions valid prefix] `P` of `Init`, adds an `__init__(...)` function overload to the extension class accepting P as arguments. Each overload generated constructs an object of HeldType according to the semantics described above, using a copy of init_expr's call policies. If the longest [link high_level_components.boost_python_init_hpp.introduction.init_expressions valid prefix] of Init contains N types and init_expr holds M keywords, an initial sequence of the keywords are used for all but the first N - M arguments of each overload.]]
 [[Returns][`*this`]]
 [[Rationale][Allows users to easily expose a class' constructor to Python.]] 
]
``
  template <class F>
  class_& def(char const* name, Fn fn);
  template <class Fn, class A1>
  class_& def(char const* name, Fn fn, A1 const& a1);
  template <class Fn, class A1, class A2>
  class_& def(char const* name, Fn fn, A1 const& a1, A2 const& a2);
  template <class Fn, class A1, class A2, class A3>
  class_& def(char const* name, Fn fn, A1 const& a1, A2 const& a2, A3 const& a3);
``
[variablelist
 [[Requires][name is an [link ntbs] which conforms to Python's [@http://www.python.org/doc/current/ref/identifiers.html identifier naming rules].
 * If a1 is the result of an [link function_invocation_and_creation.boost_python_overloads_hpp.introduction.overload_dispatch_expressions overload-dispatch-expression], only the second form is allowed and fn must be a pointer to function or pointer to member function whose [link arity] is the same as A1's [link function_invocation_and_creation.boost_python_overloads_hpp.introduction.overload_dispatch_expressions maximum arity].

   [*Effects:] For each prefix `P` of `Fn`\ 's sequence of argument types, beginning with the one whose length is `A1`\ 's [link function_invocation_and_creation.boost_python_overloads_hpp.introduction.overload_dispatch_expressions minimum arity], adds a `name(...)` method overload to the extension class. Each overload generated invokes a1's call-expression with `P`, using a copy of a1's call policies. If the longest valid prefix of `A1` contains `N` types and a1 holds `M` keywords, an initial sequence of the keywords are used for all but the first `N - M` arguments of each overload.

* Otherwise, a single method overload is built around fn, which must not be null:

    * If fn is a function pointer, its first argument must be of the form U, U cv&, U cv*, or U cv* const&, where T* is convertible to U*, and a1-a3, if supplied, may be selected in any order from the table below.
    * Otherwise, if fn is a member function pointer, its target must be T or one of its public base classes, and a1-a3, if supplied, may be selected in any order from the table below.
    * Otherwise, Fn must be [derived from] [link object_wrappers.boost_python_object_hpp.class_object object], and a1-a2, if supplied, may be selcted in any order from the first two rows of the table below. To be useful, fn should be [@http://www.python.org/doc/current/lib/built-in-funcs.html#l2h-6 callable].
  [table
    [[Mnemonic Name][Requirements/Type properties][Effects]]
    [[docstring][Any [link ntbs]][Value will be bound to the __doc__ attribute of the resulting method overload. If an earlier overload supplied a docstring, two newline characters and the new docstring are appended to it.]]
    [[policies][A model of [link concepts.callpolicies CallPolicies]][A copy will be used as the call policies of the resulting method overload.]]
    [[keywords][The result of a [link function_invocation_and_creation.boost_python_args_hpp.introduction.keyword_expressions keyword-expression] specifying no more arguments than the [link arity] of fn.][A copy will be used as the call policies of the resulting method overload.]]
  ]
]]
 [[Returns][`*this`]]
]
``class_& staticmethod(char const* name);``
[variablelist
  [[Requires][name is an [link ntbs] which conforms to Python's [@http://www.python.org/doc/current/ref/identifiers.html identifier naming rules], and corresponds to a method whose overloads have all been defined.]]
  [[Effects][Replaces the existing named attribute `x` with the result of invoking `staticmethod(x)` in Python. Specifies that the corresponding method is static and therefore no object instance will be passed to it. This is equivalent to the Python statement:]]
]
``setattr(self, name, staticmethod(getattr(self, name)))``
[variablelist
 [[Note][Attempting to invoke def(name,...) after invoking staticmethod(name) will [link raise] a RuntimeError.]]
 [[Returns][`*this`]]
]
``
template <unspecified>
class_& def(detail::operator_<unspecified>);
``
[variablelist
  [[Effects][Adds a Python [@http://www.python.org/doc/ref/specialnames.html special method] as described [link high_level_components.boost_python_operators_hpp here].]]
  [[Returns][`*this`]]
]

``
  template <class U>
  class_& setattr(char const* name, U const& u);
``
[variablelist
  [[Requires][name is an [link ntbs] which conforms to Python's [@http://www.python.org/doc/current/ref/identifiers.html identifier naming rules].]]
  [[Effects][Converts `u` to Python and adds it to the attribute dictionary of the extension class:
  ``PyObject_SetAttrString(this->ptr(), name, object(u).ptr());``]]
  [[Returns][`*this`]]
]
``
  template <class Get>
  void add_property(char const* name, Get const& fget, char const* doc=0);
  template <class Get, class Set>
  void add_property(
        char const* name, Get const& fget, Set const& fset, char const* doc=0);
``
[variablelist
  [[Requires][name is an [link ntbs] which conform to Python's [@http://www.python.org/doc/current/ref/identifiers.html identifier naming rules].]]
  [[Effects][Creates a new Python [@http://www.python.org/2.2.2/descrintro.html#property property] class instance, passing `object(fget)` (and `object(fset)` in the second form) with an (optional) docstring `doc` to its constructor, then adds that property to the Python class object under construction with the given attribute name.]]
  [[Returns][`*this`]]
  [[Rationale][Allows users to easily expose functions that can be invoked from Python with attribute access syntax.]]
]
``
  template <class Get>
  void add_static_property(char const* name, Get const& fget);
  template <class Get, class Set>
  void add_static_property(char const* name, Get const& fget, Set const& fset);
``
[variablelist
  [[Requires][name is an [link ntbs] which conforms to Python's [@http://www.python.org/doc/current/ref/identifiers.html identifier naming rules].]]
  [[Effects][Creates a Boost.Python.StaticProperty object, passing `object(fget)` (and `object(fset)` in the second form) to its constructor, then adds that property to the Python class under construction with the given attribute name. StaticProperty is a special subclass of Python's property class which can be called without an initial self argument.]]
  [[Returns][`*this`]]
  [[Rationale][Allows users to easily expose functions that can be invoked from Python with static attribute access syntax.]]
]
``
  template <class D>
  class_& def_readonly(char const* name, D T::*pm, char const* doc=0);
  template <class D>
  class_& def_readonly(char const* name, D const& d);
``
[variablelist
  [[Requires][name is an [link ntbs] which conforms to Python's [@http://www.python.org/doc/current/ref/identifiers.html identifier naming rules]. `doc` is also an [link ntbs].]]
  [[Effects][``this->add_property(name, make_getter(pm), doc);`` and ``this->add_static_property(name, make_getter(d));`` respectively.]]
  [[Returns][`*this`]]
  [[Rationale][Allows users to easily expose a class' data member or free variable such that it can be inspected from Python with a natural syntax.]]
]
``
  template <class D>
  class_& def_readwrite(char const* name, D T::*pm, char const* doc=0);
  template <class D>
  class_& def_readwrite(char const* name, D& d);
``
[variablelist
[[Effects][``this->add_property(name, make_getter(pm), make_setter(pm), doc);`` and ``this->add_static_property(name, make_getter(d), make_setter(d));`` respectively.]]
[[Returns][`*this`]]
[[Rationale][Allows users to easily expose a class' data or free variable member such that it can be inspected and set from Python with a natural syntax.]]
]
``
  template <typename PickleSuite>
  class_& def_pickle(PickleSuite const&);
``
[variablelist
[[Requires][PickleSuite must be publically derived from [link topics.pickle_support.the_pickle_interface pickle_suite].]]
[[Effects][Defines a legal combination of the special attributes and methods: __getinitargs__, __getstate__, __setstate__, __getstate_manages_dict__, __safe_for_unpickling__, __reduce__]]
[[Returns][`*this`]]
[[Rationale][Provides an [link topics.pickle_support.the_pickle_interface easy to use high-level interface] for establishing complete [link topics.pickle_support.the_pickle_interface pickle support] for the wrapped class. The user is protected by compile-time consistency checks.]]
]
``class_& enable_pickling();``
[variablelist
[[Effects][Defines the __reduce__ method and the __safe_for_unpickling__ attribute.]]
[[Returns][`*this`]]
[[Rationale][Light-weight alternative to def_pickle(). Enables implementation of pickle support from Python.]]
]
[endsect]
[endsect]
[section Class template bases<T1, T2, ...TN>]
An MPL sequence which can be used in class_<...> instantiations indicate a list of base classes.
[section Class template bases synopsis]
``
namespace boost { namespace python
{
  template <T1 = unspecified,...Tn = unspecified>
  struct bases
  {};
}}
``
[endsect]
[endsect]
[section Examples]
Given a C++ class declaration:
``
class Foo : public Bar, public Baz
{
 public:
   Foo(int x, char const* y);
   Foo(double);

   std::string const& name() { return m_name; }
   void name(char const*);

   double value; // public data
 private:
   ...
};
``
A corresponding Boost.Python extension class can be created with:
``
using namespace boost::python;

class_<Foo,bases<Bar,Baz> >("Foo",
          "This is Foo's docstring."
          "It describes our Foo extension class",

          init<int,char const*>(args("x","y"), "__init__ docstring")
          )
   .def(init<double>())
   .def("get_name", &Foo::get_name, return_internal_reference<>())
   .def("set_name", &Foo::set_name)
   .def_readwrite("value", &Foo::value);
``
[endsect]
[endsect]