knowrob  2.1.0
A Knowledge Base System for Cognition-enabled Robots
optional.h
Go to the documentation of this file.
1 /*
2  * This file is part of KnowRob, please consult
3  * https://github.com/knowrob/knowrob for license details.
4  */
5 
6 #ifndef KNOWROB_PY_CONVERTER_OPTIONAL_H
7 #define KNOWROB_PY_CONVERTER_OPTIONAL_H
8 
9 #include <boost/python.hpp>
10 #include "optional"
11 
12 namespace knowrob::py {
14  template<typename T>
15  struct python_optional : private boost::noncopyable {
16  struct conversion : public boost::python::converter::expected_from_python_type<T> {
17  static PyObject *convert(std::optional<T> const &value) {
18  using namespace boost::python;
19  return incref((value ? object(*value) : object()).ptr());
20  }
21  };
22 
23  static void *convertible(PyObject *obj) {
24  using namespace boost::python;
25  return obj == Py_None || extract<T>(obj).check() ? obj : NULL;
26  }
27 
28  static void constructor(
29  PyObject *obj,
30  boost::python::converter::rvalue_from_python_stage1_data *data
31  ) {
32  using namespace boost::python;
33  void *const storage =
34  reinterpret_cast<
35  converter::rvalue_from_python_storage<std::optional<T> > *
36  >(data)->storage.bytes;
37  if (obj == Py_None) {
38  new(storage) std::optional<T>();
39  } else {
40  new(storage) std::optional<T>(extract<T>(obj));
41  }
42  data->convertible = storage;
43  }
44 
45  explicit python_optional() {
46  using namespace boost::python;
47  if (!extract<std::optional<T> >(object()).check()) {
48  to_python_converter<std::optional<T>, conversion, true>();
49  converter::registry::push_back(
50  &convertible,
51  &constructor,
52  type_id<std::optional<T> >(),
53  &conversion::get_pytype
54  );
55  }
56  }
57  };
58 }
59 
60 #endif //KNOWROB_PY_CONVERTER_OPTIONAL_H
static PyObject * convert(std::optional< T > const &value)
Definition: optional.h:17
static void * convertible(PyObject *obj)
Definition: optional.h:23
static void constructor(PyObject *obj, boost::python::converter::rvalue_from_python_stage1_data *data)
Definition: optional.h:28