stl.h 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. /*
  2. pybind11/stl.h: Transparent conversion for STL data types
  3. Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
  4. All rights reserved. Use of this source code is governed by a
  5. BSD-style license that can be found in the LICENSE file.
  6. */
  7. #pragma once
  8. #include "pybind11.h"
  9. #include "detail/common.h"
  10. #include "detail/descr.h"
  11. #include "detail/type_caster_base.h"
  12. #include <deque>
  13. #include <initializer_list>
  14. #include <list>
  15. #include <map>
  16. #include <memory>
  17. #include <ostream>
  18. #include <set>
  19. #include <unordered_map>
  20. #include <unordered_set>
  21. #include <valarray>
  22. // See `detail/common.h` for implementation of these guards.
  23. #if defined(PYBIND11_HAS_OPTIONAL)
  24. # include <optional>
  25. #elif defined(PYBIND11_HAS_EXP_OPTIONAL)
  26. # include <experimental/optional>
  27. #endif
  28. #if defined(PYBIND11_HAS_VARIANT)
  29. # include <variant>
  30. #endif
  31. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
  32. PYBIND11_NAMESPACE_BEGIN(detail)
  33. //
  34. // Begin: Equivalent of
  35. // https://github.com/google/clif/blob/ae4eee1de07cdf115c0c9bf9fec9ff28efce6f6c/clif/python/runtime.cc#L388-L438
  36. /*
  37. The three `object_is_convertible_to_*()` functions below are
  38. the result of converging the behaviors of pybind11 and PyCLIF
  39. (http://github.com/google/clif).
  40. Originally PyCLIF was extremely far on the permissive side of the spectrum,
  41. while pybind11 was very far on the strict side. Originally PyCLIF accepted any
  42. Python iterable as input for a C++ `vector`/`set`/`map` argument, as long as
  43. the elements were convertible. The obvious (in hindsight) problem was that
  44. any empty Python iterable could be passed to any of these C++ types, e.g. `{}`
  45. was accepted for C++ `vector`/`set` arguments, or `[]` for C++ `map` arguments.
  46. The functions below strike a practical permissive-vs-strict compromise,
  47. informed by tens of thousands of use cases in the wild. A main objective is
  48. to prevent accidents and improve readability:
  49. - Python literals must match the C++ types.
  50. - For C++ `set`: The potentially reducing conversion from a Python sequence
  51. (e.g. Python `list` or `tuple`) to a C++ `set` must be explicit, by going
  52. through a Python `set`.
  53. - However, a Python `set` can still be passed to a C++ `vector`. The rationale
  54. is that this conversion is not reducing. Implicit conversions of this kind
  55. are also fairly commonly used, therefore enforcing explicit conversions
  56. would have an unfavorable cost : benefit ratio; more sloppily speaking,
  57. such an enforcement would be more annoying than helpful.
  58. Additional checks have been added to allow types derived from `collections.abc.Set` and
  59. `collections.abc.Mapping` (`collections.abc.Sequence` is already allowed by `PySequence_Check`).
  60. */
  61. inline bool object_is_instance_with_one_of_tp_names(PyObject *obj,
  62. std::initializer_list<const char *> tp_names) {
  63. if (PyType_Check(obj)) {
  64. return false;
  65. }
  66. const char *obj_tp_name = Py_TYPE(obj)->tp_name;
  67. for (const auto *tp_name : tp_names) {
  68. if (std::strcmp(obj_tp_name, tp_name) == 0) {
  69. return true;
  70. }
  71. }
  72. return false;
  73. }
  74. inline bool object_is_convertible_to_std_vector(const handle &src) {
  75. // Allow sequence-like objects, but not (byte-)string-like objects.
  76. if (PySequence_Check(src.ptr()) != 0) {
  77. return !PyUnicode_Check(src.ptr()) && !PyBytes_Check(src.ptr());
  78. }
  79. // Allow generators, set/frozenset and several common iterable types.
  80. return (PyGen_Check(src.ptr()) != 0) || (PyAnySet_Check(src.ptr()) != 0)
  81. || object_is_instance_with_one_of_tp_names(
  82. src.ptr(), {"dict_keys", "dict_values", "dict_items", "map", "zip"});
  83. }
  84. inline bool object_is_convertible_to_std_set(const handle &src, bool convert) {
  85. // Allow set/frozenset and dict keys.
  86. // In convert mode: also allow types derived from collections.abc.Set.
  87. return ((PyAnySet_Check(src.ptr()) != 0)
  88. || object_is_instance_with_one_of_tp_names(src.ptr(), {"dict_keys"}))
  89. || (convert && isinstance(src, module_::import("collections.abc").attr("Set")));
  90. }
  91. inline bool object_is_convertible_to_std_map(const handle &src, bool convert) {
  92. // Allow dict.
  93. if (PyDict_Check(src.ptr())) {
  94. return true;
  95. }
  96. // Allow types conforming to Mapping Protocol.
  97. // According to https://docs.python.org/3/c-api/mapping.html, `PyMappingCheck()` checks for
  98. // `__getitem__()` without checking the type of keys. In order to restrict the allowed types
  99. // closer to actual Mapping-like types, we also check for the `items()` method.
  100. if (PyMapping_Check(src.ptr()) != 0) {
  101. PyObject *items = PyObject_GetAttrString(src.ptr(), "items");
  102. if (items != nullptr) {
  103. bool is_convertible = (PyCallable_Check(items) != 0);
  104. Py_DECREF(items);
  105. if (is_convertible) {
  106. return true;
  107. }
  108. } else {
  109. PyErr_Clear();
  110. }
  111. }
  112. // In convert mode: Allow types derived from collections.abc.Mapping
  113. return convert && isinstance(src, module_::import("collections.abc").attr("Mapping"));
  114. }
  115. //
  116. // End: Equivalent of clif/python/runtime.cc
  117. //
  118. /// Extracts an const lvalue reference or rvalue reference for U based on the type of T (e.g. for
  119. /// forwarding a container element). Typically used indirect via forwarded_type(), below.
  120. template <typename T, typename U>
  121. using forwarded_type = conditional_t<std::is_lvalue_reference<T>::value,
  122. remove_reference_t<U> &,
  123. remove_reference_t<U> &&>;
  124. /// Forwards a value U as rvalue or lvalue according to whether T is rvalue or lvalue; typically
  125. /// used for forwarding a container's elements.
  126. template <typename T, typename U>
  127. constexpr forwarded_type<T, U> forward_like(U &&u) {
  128. return std::forward<detail::forwarded_type<T, U>>(std::forward<U>(u));
  129. }
  130. // Checks if a container has a STL style reserve method.
  131. // This will only return true for a `reserve()` with a `void` return.
  132. template <typename C>
  133. using has_reserve_method = std::is_same<decltype(std::declval<C>().reserve(0)), void>;
  134. template <typename Type, typename Key>
  135. struct set_caster {
  136. using type = Type;
  137. using key_conv = make_caster<Key>;
  138. private:
  139. template <typename T = Type, enable_if_t<has_reserve_method<T>::value, int> = 0>
  140. void reserve_maybe(const anyset &s, Type *) {
  141. value.reserve(s.size());
  142. }
  143. void reserve_maybe(const anyset &, void *) {}
  144. bool convert_iterable(const iterable &itbl, bool convert) {
  145. for (const auto &it : itbl) {
  146. key_conv conv;
  147. if (!conv.load(it, convert)) {
  148. return false;
  149. }
  150. value.insert(cast_op<Key &&>(std::move(conv)));
  151. }
  152. return true;
  153. }
  154. bool convert_anyset(const anyset &s, bool convert) {
  155. value.clear();
  156. reserve_maybe(s, &value);
  157. return convert_iterable(s, convert);
  158. }
  159. public:
  160. bool load(handle src, bool convert) {
  161. if (!object_is_convertible_to_std_set(src, convert)) {
  162. return false;
  163. }
  164. if (isinstance<anyset>(src)) {
  165. value.clear();
  166. return convert_anyset(reinterpret_borrow<anyset>(src), convert);
  167. }
  168. if (!convert) {
  169. return false;
  170. }
  171. assert(isinstance<iterable>(src));
  172. value.clear();
  173. return convert_iterable(reinterpret_borrow<iterable>(src), convert);
  174. }
  175. template <typename T>
  176. static handle cast(T &&src, return_value_policy policy, handle parent) {
  177. if (!std::is_lvalue_reference<T>::value) {
  178. policy = return_value_policy_override<Key>::policy(policy);
  179. }
  180. pybind11::set s;
  181. for (auto &&value : src) {
  182. auto value_ = reinterpret_steal<object>(
  183. key_conv::cast(detail::forward_like<T>(value), policy, parent));
  184. if (!value_ || !s.add(std::move(value_))) {
  185. return handle();
  186. }
  187. }
  188. return s.release();
  189. }
  190. PYBIND11_TYPE_CASTER(type,
  191. io_name("collections.abc.Set", "set") + const_name("[") + key_conv::name
  192. + const_name("]"));
  193. };
  194. template <typename Type, typename Key, typename Value>
  195. struct map_caster {
  196. using key_conv = make_caster<Key>;
  197. using value_conv = make_caster<Value>;
  198. private:
  199. template <typename T = Type, enable_if_t<has_reserve_method<T>::value, int> = 0>
  200. void reserve_maybe(const dict &d, Type *) {
  201. value.reserve(d.size());
  202. }
  203. void reserve_maybe(const dict &, void *) {}
  204. bool convert_elements(const dict &d, bool convert) {
  205. value.clear();
  206. reserve_maybe(d, &value);
  207. for (const auto &it : d) {
  208. key_conv kconv;
  209. value_conv vconv;
  210. if (!kconv.load(it.first.ptr(), convert) || !vconv.load(it.second.ptr(), convert)) {
  211. return false;
  212. }
  213. value.emplace(cast_op<Key &&>(std::move(kconv)), cast_op<Value &&>(std::move(vconv)));
  214. }
  215. return true;
  216. }
  217. public:
  218. bool load(handle src, bool convert) {
  219. if (!object_is_convertible_to_std_map(src, convert)) {
  220. return false;
  221. }
  222. if (isinstance<dict>(src)) {
  223. return convert_elements(reinterpret_borrow<dict>(src), convert);
  224. }
  225. if (!convert) {
  226. return false;
  227. }
  228. auto items = reinterpret_steal<object>(PyMapping_Items(src.ptr()));
  229. if (!items) {
  230. throw error_already_set();
  231. }
  232. assert(isinstance<iterable>(items));
  233. return convert_elements(dict(reinterpret_borrow<iterable>(items)), convert);
  234. }
  235. template <typename T>
  236. static handle cast(T &&src, return_value_policy policy, handle parent) {
  237. dict d;
  238. return_value_policy policy_key = policy;
  239. return_value_policy policy_value = policy;
  240. if (!std::is_lvalue_reference<T>::value) {
  241. policy_key = return_value_policy_override<Key>::policy(policy_key);
  242. policy_value = return_value_policy_override<Value>::policy(policy_value);
  243. }
  244. for (auto &&kv : src) {
  245. auto key = reinterpret_steal<object>(
  246. key_conv::cast(detail::forward_like<T>(kv.first), policy_key, parent));
  247. auto value = reinterpret_steal<object>(
  248. value_conv::cast(detail::forward_like<T>(kv.second), policy_value, parent));
  249. if (!key || !value) {
  250. return handle();
  251. }
  252. d[std::move(key)] = std::move(value);
  253. }
  254. return d.release();
  255. }
  256. PYBIND11_TYPE_CASTER(Type,
  257. io_name("collections.abc.Mapping", "dict") + const_name("[")
  258. + key_conv::name + const_name(", ") + value_conv::name
  259. + const_name("]"));
  260. };
  261. template <typename Type, typename Value>
  262. struct list_caster {
  263. using value_conv = make_caster<Value>;
  264. bool load(handle src, bool convert) {
  265. if (!object_is_convertible_to_std_vector(src)) {
  266. return false;
  267. }
  268. if (isinstance<sequence>(src)) {
  269. return convert_elements(src, convert);
  270. }
  271. if (!convert) {
  272. return false;
  273. }
  274. // Designed to be behavior-equivalent to passing tuple(src) from Python:
  275. // The conversion to a tuple will first exhaust the generator object, to ensure that
  276. // the generator is not left in an unpredictable (to the caller) partially-consumed
  277. // state.
  278. assert(isinstance<iterable>(src));
  279. return convert_elements(tuple(reinterpret_borrow<iterable>(src)), convert);
  280. }
  281. private:
  282. template <typename T = Type, enable_if_t<has_reserve_method<T>::value, int> = 0>
  283. void reserve_maybe(const sequence &s, Type *) {
  284. value.reserve(s.size());
  285. }
  286. void reserve_maybe(const sequence &, void *) {}
  287. bool convert_elements(handle seq, bool convert) {
  288. auto s = reinterpret_borrow<sequence>(seq);
  289. value.clear();
  290. reserve_maybe(s, &value);
  291. for (const auto &it : seq) {
  292. value_conv conv;
  293. if (!conv.load(it, convert)) {
  294. return false;
  295. }
  296. value.push_back(cast_op<Value &&>(std::move(conv)));
  297. }
  298. return true;
  299. }
  300. public:
  301. template <typename T>
  302. static handle cast(T &&src, return_value_policy policy, handle parent) {
  303. if (!std::is_lvalue_reference<T>::value) {
  304. policy = return_value_policy_override<Value>::policy(policy);
  305. }
  306. list l(src.size());
  307. ssize_t index = 0;
  308. for (auto &&value : src) {
  309. auto value_ = reinterpret_steal<object>(
  310. value_conv::cast(detail::forward_like<T>(value), policy, parent));
  311. if (!value_) {
  312. return handle();
  313. }
  314. PyList_SET_ITEM(l.ptr(), index++, value_.release().ptr()); // steals a reference
  315. }
  316. return l.release();
  317. }
  318. PYBIND11_TYPE_CASTER(Type,
  319. io_name("collections.abc.Sequence", "list") + const_name("[")
  320. + value_conv::name + const_name("]"));
  321. };
  322. template <typename Type, typename Alloc>
  323. struct type_caster<std::vector<Type, Alloc>> : list_caster<std::vector<Type, Alloc>, Type> {};
  324. template <typename Type, typename Alloc>
  325. struct type_caster<std::deque<Type, Alloc>> : list_caster<std::deque<Type, Alloc>, Type> {};
  326. template <typename Type, typename Alloc>
  327. struct type_caster<std::list<Type, Alloc>> : list_caster<std::list<Type, Alloc>, Type> {};
  328. template <typename ArrayType, typename V, size_t... I>
  329. ArrayType vector_to_array_impl(V &&v, index_sequence<I...>) {
  330. return {{std::move(v[I])...}};
  331. }
  332. // Based on https://en.cppreference.com/w/cpp/container/array/to_array
  333. template <typename ArrayType, size_t N, typename V>
  334. ArrayType vector_to_array(V &&v) {
  335. return vector_to_array_impl<ArrayType, V>(std::forward<V>(v), make_index_sequence<N>{});
  336. }
  337. template <typename ArrayType, typename Value, bool Resizable, size_t Size = 0>
  338. struct array_caster {
  339. using value_conv = make_caster<Value>;
  340. private:
  341. std::unique_ptr<ArrayType> value;
  342. template <bool R = Resizable, enable_if_t<R, int> = 0>
  343. bool convert_elements(handle seq, bool convert) {
  344. auto l = reinterpret_borrow<sequence>(seq);
  345. value.reset(new ArrayType{});
  346. // Using `resize` to preserve the behavior exactly as it was before PR #5305
  347. // For the `resize` to work, `Value` must be default constructible.
  348. // For `std::valarray`, this is a requirement:
  349. // https://en.cppreference.com/w/cpp/named_req/NumericType
  350. value->resize(l.size());
  351. size_t ctr = 0;
  352. for (const auto &it : l) {
  353. value_conv conv;
  354. if (!conv.load(it, convert)) {
  355. return false;
  356. }
  357. (*value)[ctr++] = cast_op<Value &&>(std::move(conv));
  358. }
  359. return true;
  360. }
  361. template <bool R = Resizable, enable_if_t<!R, int> = 0>
  362. bool convert_elements(handle seq, bool convert) {
  363. auto l = reinterpret_borrow<sequence>(seq);
  364. if (l.size() != Size) {
  365. return false;
  366. }
  367. // The `temp` storage is needed to support `Value` types that are not
  368. // default-constructible.
  369. // Deliberate choice: no template specializations, for simplicity, and
  370. // because the compile time overhead for the specializations is deemed
  371. // more significant than the runtime overhead for the `temp` storage.
  372. std::vector<Value> temp;
  373. temp.reserve(l.size());
  374. for (auto it : l) {
  375. value_conv conv;
  376. if (!conv.load(it, convert)) {
  377. return false;
  378. }
  379. temp.emplace_back(cast_op<Value &&>(std::move(conv)));
  380. }
  381. value.reset(new ArrayType(vector_to_array<ArrayType, Size>(std::move(temp))));
  382. return true;
  383. }
  384. public:
  385. bool load(handle src, bool convert) {
  386. if (!object_is_convertible_to_std_vector(src)) {
  387. return false;
  388. }
  389. if (isinstance<sequence>(src)) {
  390. return convert_elements(src, convert);
  391. }
  392. if (!convert) {
  393. return false;
  394. }
  395. // Designed to be behavior-equivalent to passing tuple(src) from Python:
  396. // The conversion to a tuple will first exhaust the generator object, to ensure that
  397. // the generator is not left in an unpredictable (to the caller) partially-consumed
  398. // state.
  399. assert(isinstance<iterable>(src));
  400. return convert_elements(tuple(reinterpret_borrow<iterable>(src)), convert);
  401. }
  402. template <typename T>
  403. static handle cast(T &&src, return_value_policy policy, handle parent) {
  404. list l(src.size());
  405. ssize_t index = 0;
  406. for (auto &&value : src) {
  407. auto value_ = reinterpret_steal<object>(
  408. value_conv::cast(detail::forward_like<T>(value), policy, parent));
  409. if (!value_) {
  410. return handle();
  411. }
  412. PyList_SET_ITEM(l.ptr(), index++, value_.release().ptr()); // steals a reference
  413. }
  414. return l.release();
  415. }
  416. // Code copied from PYBIND11_TYPE_CASTER macro.
  417. // Intentionally preserving the behavior exactly as it was before PR #5305
  418. template <typename T_, enable_if_t<std::is_same<ArrayType, remove_cv_t<T_>>::value, int> = 0>
  419. static handle cast(T_ *src, return_value_policy policy, handle parent) {
  420. if (!src) {
  421. return none().release();
  422. }
  423. if (policy == return_value_policy::take_ownership) {
  424. auto h = cast(std::move(*src), policy, parent);
  425. delete src; // WARNING: Assumes `src` was allocated with `new`.
  426. return h;
  427. }
  428. return cast(*src, policy, parent);
  429. }
  430. // NOLINTNEXTLINE(google-explicit-constructor)
  431. operator ArrayType *() { return &(*value); }
  432. // NOLINTNEXTLINE(google-explicit-constructor)
  433. operator ArrayType &() { return *value; }
  434. // NOLINTNEXTLINE(google-explicit-constructor)
  435. operator ArrayType &&() && { return std::move(*value); }
  436. template <typename T_>
  437. using cast_op_type = movable_cast_op_type<T_>;
  438. static constexpr auto name
  439. = const_name<Resizable>(const_name(""), const_name("typing.Annotated["))
  440. + io_name("collections.abc.Sequence", "list") + const_name("[") + value_conv::name
  441. + const_name("]")
  442. + const_name<Resizable>(const_name(""),
  443. const_name(", \"FixedSize(") + const_name<Size>()
  444. + const_name(")\"]"));
  445. };
  446. template <typename Type, size_t Size>
  447. struct type_caster<std::array<Type, Size>>
  448. : array_caster<std::array<Type, Size>, Type, false, Size> {};
  449. template <typename Type>
  450. struct type_caster<std::valarray<Type>> : array_caster<std::valarray<Type>, Type, true> {};
  451. template <typename Key, typename Compare, typename Alloc>
  452. struct type_caster<std::set<Key, Compare, Alloc>>
  453. : set_caster<std::set<Key, Compare, Alloc>, Key> {};
  454. template <typename Key, typename Hash, typename Equal, typename Alloc>
  455. struct type_caster<std::unordered_set<Key, Hash, Equal, Alloc>>
  456. : set_caster<std::unordered_set<Key, Hash, Equal, Alloc>, Key> {};
  457. template <typename Key, typename Value, typename Compare, typename Alloc>
  458. struct type_caster<std::map<Key, Value, Compare, Alloc>>
  459. : map_caster<std::map<Key, Value, Compare, Alloc>, Key, Value> {};
  460. template <typename Key, typename Value, typename Hash, typename Equal, typename Alloc>
  461. struct type_caster<std::unordered_map<Key, Value, Hash, Equal, Alloc>>
  462. : map_caster<std::unordered_map<Key, Value, Hash, Equal, Alloc>, Key, Value> {};
  463. // This type caster is intended to be used for std::optional and std::experimental::optional
  464. template <typename Type, typename Value = typename Type::value_type>
  465. struct optional_caster {
  466. using value_conv = make_caster<Value>;
  467. template <typename T>
  468. static handle cast(T &&src, return_value_policy policy, handle parent) {
  469. if (!src) {
  470. return none().release();
  471. }
  472. if (!std::is_lvalue_reference<T>::value) {
  473. policy = return_value_policy_override<Value>::policy(policy);
  474. }
  475. // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
  476. return value_conv::cast(*std::forward<T>(src), policy, parent);
  477. }
  478. bool load(handle src, bool convert) {
  479. if (!src) {
  480. return false;
  481. }
  482. if (src.is_none()) {
  483. return true; // default-constructed value is already empty
  484. }
  485. value_conv inner_caster;
  486. if (!inner_caster.load(src, convert)) {
  487. return false;
  488. }
  489. value.emplace(cast_op<Value &&>(std::move(inner_caster)));
  490. return true;
  491. }
  492. PYBIND11_TYPE_CASTER(Type, value_conv::name | make_caster<none>::name);
  493. };
  494. #if defined(PYBIND11_HAS_OPTIONAL)
  495. template <typename T>
  496. struct type_caster<std::optional<T>> : public optional_caster<std::optional<T>> {};
  497. template <>
  498. struct type_caster<std::nullopt_t> : public void_caster<std::nullopt_t> {};
  499. #endif
  500. #if defined(PYBIND11_HAS_EXP_OPTIONAL)
  501. template <typename T>
  502. struct type_caster<std::experimental::optional<T>>
  503. : public optional_caster<std::experimental::optional<T>> {};
  504. template <>
  505. struct type_caster<std::experimental::nullopt_t>
  506. : public void_caster<std::experimental::nullopt_t> {};
  507. #endif
  508. /// Visit a variant and cast any found type to Python
  509. struct variant_caster_visitor {
  510. return_value_policy policy;
  511. handle parent;
  512. using result_type = handle; // required by boost::variant in C++11
  513. template <typename T>
  514. result_type operator()(T &&src) const {
  515. return make_caster<T>::cast(std::forward<T>(src), policy, parent);
  516. }
  517. };
  518. /// Helper class which abstracts away variant's `visit` function. `std::variant` and similar
  519. /// `namespace::variant` types which provide a `namespace::visit()` function are handled here
  520. /// automatically using argument-dependent lookup. Users can provide specializations for other
  521. /// variant-like classes, e.g. `boost::variant` and `boost::apply_visitor`.
  522. template <template <typename...> class Variant>
  523. struct visit_helper {
  524. template <typename... Args>
  525. static auto call(Args &&...args) -> decltype(visit(std::forward<Args>(args)...)) {
  526. return visit(std::forward<Args>(args)...);
  527. }
  528. };
  529. /// Generic variant caster
  530. template <typename Variant>
  531. struct variant_caster;
  532. template <template <typename...> class V, typename... Ts>
  533. struct variant_caster<V<Ts...>> {
  534. static_assert(sizeof...(Ts) > 0, "Variant must consist of at least one alternative.");
  535. template <typename U, typename... Us>
  536. bool load_alternative(handle src, bool convert, type_list<U, Us...>) {
  537. auto caster = make_caster<U>();
  538. if (caster.load(src, convert)) {
  539. value = cast_op<U>(std::move(caster));
  540. return true;
  541. }
  542. return load_alternative(src, convert, type_list<Us...>{});
  543. }
  544. bool load_alternative(handle, bool, type_list<>) { return false; }
  545. bool load(handle src, bool convert) {
  546. // Do a first pass without conversions to improve constructor resolution.
  547. // E.g. `py::int_(1).cast<variant<double, int>>()` needs to fill the `int`
  548. // slot of the variant. Without two-pass loading `double` would be filled
  549. // because it appears first and a conversion is possible.
  550. if (convert && load_alternative(src, false, type_list<Ts...>{})) {
  551. return true;
  552. }
  553. return load_alternative(src, convert, type_list<Ts...>{});
  554. }
  555. template <typename Variant>
  556. static handle cast(Variant &&src, return_value_policy policy, handle parent) {
  557. return visit_helper<V>::call(variant_caster_visitor{policy, parent},
  558. std::forward<Variant>(src));
  559. }
  560. using Type = V<Ts...>;
  561. PYBIND11_TYPE_CASTER(Type, ::pybind11::detail::union_concat(make_caster<Ts>::name...));
  562. };
  563. #if defined(PYBIND11_HAS_VARIANT)
  564. template <typename... Ts>
  565. struct type_caster<std::variant<Ts...>> : variant_caster<std::variant<Ts...>> {};
  566. template <>
  567. struct type_caster<std::monostate> : public void_caster<std::monostate> {};
  568. #endif
  569. PYBIND11_NAMESPACE_END(detail)
  570. inline std::ostream &operator<<(std::ostream &os, const handle &obj) {
  571. #ifdef PYBIND11_HAS_STRING_VIEW
  572. os << str(obj).cast<std::string_view>();
  573. #else
  574. os << (std::string) str(obj);
  575. #endif
  576. return os;
  577. }
  578. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)