MTC
properties.h
1 #pragma once
2 
3 #include <py_binding_tools/ros_msg_typecasters.h>
4 #include <moveit/task_constructor/properties.h>
5 #include <boost/any.hpp>
6 #include <typeindex>
7 
8 namespace moveit {
9 namespace python {
10 
11 class PYBIND11_EXPORT PropertyConverterBase
12 {
13 public:
14  using to_python_converter_function = pybind11::object (*)(const boost::any&);
15  using from_python_converter_function = boost::any (*)(const pybind11::object&);
16 
17 protected:
18  static bool insert(const std::type_index& type_index, const std::string& ros_msg_name,
19  to_python_converter_function to, from_python_converter_function from);
20 };
21 
23 template <typename T>
25 {
26 public:
27  PropertyConverter() { insert(typeid(T), rosMsgName<T>(), &toPython, &fromPython); }
28 
29 private:
30  static pybind11::object toPython(const boost::any& value) { return pybind11::cast(boost::any_cast<T>(value)); }
31  static boost::any fromPython(const pybind11::object& po) { return pybind11::cast<T>(po); }
32 
33  template <class Q = T>
34  typename std::enable_if<ros::message_traits::IsMessage<Q>::value, std::string>::type rosMsgName() {
35  return ros::message_traits::DataType<T>::value();
36  }
37 
38  template <class Q = T>
39  typename std::enable_if<!ros::message_traits::IsMessage<Q>::value, std::string>::type rosMsgName() {
40  return std::string();
41  }
42 };
43 
44 namespace properties {
45 
51 template <typename type_, typename... options>
52 class class_ : public pybind11::classh<type_, options...> // NOLINT(readability-identifier-naming)
53 {
54  using base_class_ = pybind11::classh<type_, options...>;
55 
56 public:
57  // forward all constructors
58  using base_class_::base_class_;
59 
60  template <typename PropertyType, typename... Extra>
61  class_& property(const char* name, const Extra&... extra) {
62  PropertyConverter<PropertyType>(); // register corresponding property converter
63  auto getter = [name](type_& self) -> PropertyType& {
64  moveit::task_constructor::PropertyMap& props = self.properties();
65  return const_cast<PropertyType&>(props.get<PropertyType>(name));
66  };
67  auto setter = [name](type_& self, const PropertyType& value) {
68  moveit::task_constructor::PropertyMap& props = self.properties();
69  props.set(name, boost::any(value));
70  };
71  base_class_::def_property(name, getter, setter, pybind11::return_value_policy::reference_internal, extra...);
72  return *this;
73  }
74 };
75 } // namespace properties
76 } // namespace python
77 } // namespace moveit
Definition: properties.h:12
utility class to register C++ / Python converters for a property of type T
Definition: properties.h:25
Definition: properties.h:257
const boost::any & get(const std::string &name) const
Get the value of a property. Throws undeclared if unknown name.
Definition: properties.cpp:254
void set(const std::string &name, const T &value)
set (and, if neccessary, declare) the value of a property
Definition: properties.h:304