2 pybind11/stl.h: Transparent conversion for STL data types
4 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
6 All rights reserved. Use of this source code is governed by a
7 BSD-style license that can be found in the LICENSE file.
14 #include <unordered_set>
16 #include <unordered_map>
24 #pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
28 // std::optional (but including it in c++14 mode isn't allowed)
29 # if defined(PYBIND11_CPP17) && __has_include(<optional>)
31 # define PYBIND11_HAS_OPTIONAL 1
33 // std::experimental::optional (but not allowed in c++11 mode)
34 # if defined(PYBIND11_CPP14) && (__has_include(<experimental/optional>) && \
35 !__has_include(<optional>))
36 # include <experimental/optional>
37 # define PYBIND11_HAS_EXP_OPTIONAL 1
40 # if defined(PYBIND11_CPP17) && __has_include(<variant>)
42 # define PYBIND11_HAS_VARIANT 1
44 #elif defined(_MSC_VER) && defined(PYBIND11_CPP17)
47 # define PYBIND11_HAS_OPTIONAL 1
48 # define PYBIND11_HAS_VARIANT 1
51 NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
52 NAMESPACE_BEGIN(detail)
54 /// Extracts an const lvalue reference or rvalue reference for U based on the type of T (e.g. for
55 /// forwarding a container element). Typically used indirect via forwarded_type(), below.
56 template <typename T, typename U>
57 using forwarded_type = conditional_t<
58 std::is_lvalue_reference<T>::value, remove_reference_t<U> &, remove_reference_t<U> &&>;
60 /// Forwards a value U as rvalue or lvalue according to whether T is rvalue or lvalue; typically
61 /// used for forwarding a container's elements.
62 template <typename T, typename U>
63 forwarded_type<T, U> forward_like(U &&u) {
64 return std::forward<detail::forwarded_type<T, U>>(std::forward<U>(u));
67 template <typename Type, typename Key> struct set_caster {
69 using key_conv = make_caster<Key>;
71 bool load(handle src, bool convert) {
72 if (!isinstance<pybind11::set>(src))
74 auto s = reinterpret_borrow<pybind11::set>(src);
76 for (auto entry : s) {
78 if (!conv.load(entry, convert))
80 value.insert(cast_op<Key &&>(std::move(conv)));
86 static handle cast(T &&src, return_value_policy policy, handle parent) {
87 if (!std::is_lvalue_reference<T>::value)
88 policy = return_value_policy_override<Key>::policy(policy);
90 for (auto &&value : src) {
91 auto value_ = reinterpret_steal<object>(key_conv::cast(forward_like<T>(value), policy, parent));
92 if (!value_ || !s.add(value_))
98 PYBIND11_TYPE_CASTER(type, _("Set[") + key_conv::name + _("]"));
101 template <typename Type, typename Key, typename Value> struct map_caster {
102 using key_conv = make_caster<Key>;
103 using value_conv = make_caster<Value>;
105 bool load(handle src, bool convert) {
106 if (!isinstance<dict>(src))
108 auto d = reinterpret_borrow<dict>(src);
113 if (!kconv.load(it.first.ptr(), convert) ||
114 !vconv.load(it.second.ptr(), convert))
116 value.emplace(cast_op<Key &&>(std::move(kconv)), cast_op<Value &&>(std::move(vconv)));
121 template <typename T>
122 static handle cast(T &&src, return_value_policy policy, handle parent) {
124 return_value_policy policy_key = policy;
125 return_value_policy policy_value = policy;
126 if (!std::is_lvalue_reference<T>::value) {
127 policy_key = return_value_policy_override<Key>::policy(policy_key);
128 policy_value = return_value_policy_override<Value>::policy(policy_value);
130 for (auto &&kv : src) {
131 auto key = reinterpret_steal<object>(key_conv::cast(forward_like<T>(kv.first), policy_key, parent));
132 auto value = reinterpret_steal<object>(value_conv::cast(forward_like<T>(kv.second), policy_value, parent));
140 PYBIND11_TYPE_CASTER(Type, _("Dict[") + key_conv::name + _(", ") + value_conv::name + _("]"));
143 template <typename Type, typename Value> struct list_caster {
144 using value_conv = make_caster<Value>;
146 bool load(handle src, bool convert) {
147 if (!isinstance<sequence>(src) || isinstance<str>(src))
149 auto s = reinterpret_borrow<sequence>(src);
151 reserve_maybe(s, &value);
154 if (!conv.load(it, convert))
156 value.push_back(cast_op<Value &&>(std::move(conv)));
162 template <typename T = Type,
163 enable_if_t<std::is_same<decltype(std::declval<T>().reserve(0)), void>::value, int> = 0>
164 void reserve_maybe(sequence s, Type *) { value.reserve(s.size()); }
165 void reserve_maybe(sequence, void *) { }
168 template <typename T>
169 static handle cast(T &&src, return_value_policy policy, handle parent) {
170 if (!std::is_lvalue_reference<T>::value)
171 policy = return_value_policy_override<Value>::policy(policy);
174 for (auto &&value : src) {
175 auto value_ = reinterpret_steal<object>(value_conv::cast(forward_like<T>(value), policy, parent));
178 PyList_SET_ITEM(l.ptr(), (ssize_t) index++, value_.release().ptr()); // steals a reference
183 PYBIND11_TYPE_CASTER(Type, _("List[") + value_conv::name + _("]"));
186 template <typename Type, typename Alloc> struct type_caster<std::vector<Type, Alloc>>
187 : list_caster<std::vector<Type, Alloc>, Type> { };
189 template <typename Type, typename Alloc> struct type_caster<std::deque<Type, Alloc>>
190 : list_caster<std::deque<Type, Alloc>, Type> { };
192 template <typename Type, typename Alloc> struct type_caster<std::list<Type, Alloc>>
193 : list_caster<std::list<Type, Alloc>, Type> { };
195 template <typename ArrayType, typename Value, bool Resizable, size_t Size = 0> struct array_caster {
196 using value_conv = make_caster<Value>;
199 template <bool R = Resizable>
200 bool require_size(enable_if_t<R, size_t> size) {
201 if (value.size() != size)
205 template <bool R = Resizable>
206 bool require_size(enable_if_t<!R, size_t> size) {
211 bool load(handle src, bool convert) {
212 if (!isinstance<sequence>(src))
214 auto l = reinterpret_borrow<sequence>(src);
215 if (!require_size(l.size()))
220 if (!conv.load(it, convert))
222 value[ctr++] = cast_op<Value &&>(std::move(conv));
227 template <typename T>
228 static handle cast(T &&src, return_value_policy policy, handle parent) {
231 for (auto &&value : src) {
232 auto value_ = reinterpret_steal<object>(value_conv::cast(forward_like<T>(value), policy, parent));
235 PyList_SET_ITEM(l.ptr(), (ssize_t) index++, value_.release().ptr()); // steals a reference
240 PYBIND11_TYPE_CASTER(ArrayType, _("List[") + value_conv::name + _<Resizable>(_(""), _("[") + _<Size>() + _("]")) + _("]"));
243 template <typename Type, size_t Size> struct type_caster<std::array<Type, Size>>
244 : array_caster<std::array<Type, Size>, Type, false, Size> { };
246 template <typename Type> struct type_caster<std::valarray<Type>>
247 : array_caster<std::valarray<Type>, Type, true> { };
249 template <typename Key, typename Compare, typename Alloc> struct type_caster<std::set<Key, Compare, Alloc>>
250 : set_caster<std::set<Key, Compare, Alloc>, Key> { };
252 template <typename Key, typename Hash, typename Equal, typename Alloc> struct type_caster<std::unordered_set<Key, Hash, Equal, Alloc>>
253 : set_caster<std::unordered_set<Key, Hash, Equal, Alloc>, Key> { };
255 template <typename Key, typename Value, typename Compare, typename Alloc> struct type_caster<std::map<Key, Value, Compare, Alloc>>
256 : map_caster<std::map<Key, Value, Compare, Alloc>, Key, Value> { };
258 template <typename Key, typename Value, typename Hash, typename Equal, typename Alloc> struct type_caster<std::unordered_map<Key, Value, Hash, Equal, Alloc>>
259 : map_caster<std::unordered_map<Key, Value, Hash, Equal, Alloc>, Key, Value> { };
261 // This type caster is intended to be used for std::optional and std::experimental::optional
262 template<typename T> struct optional_caster {
263 using value_conv = make_caster<typename T::value_type>;
265 template <typename T_>
266 static handle cast(T_ &&src, return_value_policy policy, handle parent) {
268 return none().inc_ref();
269 policy = return_value_policy_override<typename T::value_type>::policy(policy);
270 return value_conv::cast(*std::forward<T_>(src), policy, parent);
273 bool load(handle src, bool convert) {
276 } else if (src.is_none()) {
277 return true; // default-constructed value is already empty
279 value_conv inner_caster;
280 if (!inner_caster.load(src, convert))
283 value.emplace(cast_op<typename T::value_type &&>(std::move(inner_caster)));
287 PYBIND11_TYPE_CASTER(T, _("Optional[") + value_conv::name + _("]"));
290 #if PYBIND11_HAS_OPTIONAL
291 template<typename T> struct type_caster<std::optional<T>>
292 : public optional_caster<std::optional<T>> {};
294 template<> struct type_caster<std::nullopt_t>
295 : public void_caster<std::nullopt_t> {};
298 #if PYBIND11_HAS_EXP_OPTIONAL
299 template<typename T> struct type_caster<std::experimental::optional<T>>
300 : public optional_caster<std::experimental::optional<T>> {};
302 template<> struct type_caster<std::experimental::nullopt_t>
303 : public void_caster<std::experimental::nullopt_t> {};
306 /// Visit a variant and cast any found type to Python
307 struct variant_caster_visitor {
308 return_value_policy policy;
311 using result_type = handle; // required by boost::variant in C++11
313 template <typename T>
314 result_type operator()(T &&src) const {
315 return make_caster<T>::cast(std::forward<T>(src), policy, parent);
319 /// Helper class which abstracts away variant's `visit` function. `std::variant` and similar
320 /// `namespace::variant` types which provide a `namespace::visit()` function are handled here
321 /// automatically using argument-dependent lookup. Users can provide specializations for other
322 /// variant-like classes, e.g. `boost::variant` and `boost::apply_visitor`.
323 template <template<typename...> class Variant>
324 struct visit_helper {
325 template <typename... Args>
326 static auto call(Args &&...args) -> decltype(visit(std::forward<Args>(args)...)) {
327 return visit(std::forward<Args>(args)...);
331 /// Generic variant caster
332 template <typename Variant> struct variant_caster;
334 template <template<typename...> class V, typename... Ts>
335 struct variant_caster<V<Ts...>> {
336 static_assert(sizeof...(Ts) > 0, "Variant must consist of at least one alternative.");
338 template <typename U, typename... Us>
339 bool load_alternative(handle src, bool convert, type_list<U, Us...>) {
340 auto caster = make_caster<U>();
341 if (caster.load(src, convert)) {
342 value = cast_op<U>(caster);
345 return load_alternative(src, convert, type_list<Us...>{});
348 bool load_alternative(handle, bool, type_list<>) { return false; }
350 bool load(handle src, bool convert) {
351 // Do a first pass without conversions to improve constructor resolution.
352 // E.g. `py::int_(1).cast<variant<double, int>>()` needs to fill the `int`
353 // slot of the variant. Without two-pass loading `double` would be filled
354 // because it appears first and a conversion is possible.
355 if (convert && load_alternative(src, false, type_list<Ts...>{}))
357 return load_alternative(src, convert, type_list<Ts...>{});
360 template <typename Variant>
361 static handle cast(Variant &&src, return_value_policy policy, handle parent) {
362 return visit_helper<V>::call(variant_caster_visitor{policy, parent},
363 std::forward<Variant>(src));
366 using Type = V<Ts...>;
367 PYBIND11_TYPE_CASTER(Type, _("Union[") + detail::concat(make_caster<Ts>::name...) + _("]"));
370 #if PYBIND11_HAS_VARIANT
371 template <typename... Ts>
372 struct type_caster<std::variant<Ts...>> : variant_caster<std::variant<Ts...>> { };
375 NAMESPACE_END(detail)
377 inline std::ostream &operator<<(std::ostream &os, const handle &obj) {
378 os << (std::string) str(obj);
382 NAMESPACE_END(PYBIND11_NAMESPACE)
384 #if defined(_MSC_VER)