blob: 8736ea86dbc63158e6c3388e6c9273f698daeb7d [file] [log] [blame]
Dean Moldovan83e328f2017-06-09 00:44:49 +02001/*
2 tests/test_stl.cpp -- STL type casters
3
4 Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
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.
8*/
9
10#include "pybind11_tests.h"
Wenzel Jakobcbd16a82018-07-17 16:56:26 +020011#include "constructor_stats.h"
Dean Moldovan83e328f2017-06-09 00:44:49 +020012#include <pybind11/stl.h>
13
Allan Leale76dff72018-10-11 10:28:12 +020014#include <vector>
15#include <string>
16
Dean Moldovan7918bcc2017-08-08 16:02:31 +020017// Test with `std::variant` in C++17 mode, or with `boost::variant` in C++11/14
18#if PYBIND11_HAS_VARIANT
19using std::variant;
Dean Moldovanc40ef612017-08-25 21:11:36 +020020#elif defined(PYBIND11_TEST_BOOST) && (!defined(_MSC_VER) || _MSC_VER >= 1910)
Dean Moldovan7918bcc2017-08-08 16:02:31 +020021# include <boost/variant.hpp>
22# define PYBIND11_HAS_VARIANT 1
23using boost::variant;
24
25namespace pybind11 { namespace detail {
26template <typename... Ts>
27struct type_caster<boost::variant<Ts...>> : variant_caster<boost::variant<Ts...>> {};
28
29template <>
30struct visit_helper<boost::variant> {
31 template <typename... Args>
32 static auto call(Args &&...args) -> decltype(boost::apply_visitor(args...)) {
33 return boost::apply_visitor(args...);
34 }
35};
36}} // namespace pybind11::detail
37#endif
Dean Moldovan83e328f2017-06-09 00:44:49 +020038
Allan Leale76dff72018-10-11 10:28:12 +020039PYBIND11_MAKE_OPAQUE(std::vector<std::string, std::allocator<std::string>>);
40
Dean Moldovan83e328f2017-06-09 00:44:49 +020041/// Issue #528: templated constructor
42struct TplCtorClass {
43 template <typename T> TplCtorClass(const T &) { }
44 bool operator==(const TplCtorClass &) const { return true; }
45};
46
47namespace std {
48 template <>
49 struct hash<TplCtorClass> { size_t operator()(const TplCtorClass &) const { return 0; } };
50}
51
52
53TEST_SUBMODULE(stl, m) {
54 // test_vector
55 m.def("cast_vector", []() { return std::vector<int>{1}; });
56 m.def("load_vector", [](const std::vector<int> &v) { return v.at(0) == 1 && v.at(1) == 2; });
Dean Moldovan3c4933c2017-09-01 21:42:20 +020057 // `std::vector<bool>` is special because it returns proxy objects instead of references
58 m.def("cast_bool_vector", []() { return std::vector<bool>{true, false}; });
59 m.def("load_bool_vector", [](const std::vector<bool> &v) {
60 return v.at(0) == true && v.at(1) == false;
61 });
Jason Rhinelander67a0cc42017-07-06 20:41:52 -040062 // Unnumbered regression (caused by #936): pointers to stl containers aren't castable
63 static std::vector<RValueCaster> lvv{2};
64 m.def("cast_ptr_vector", []() { return &lvv; });
Dean Moldovan83e328f2017-06-09 00:44:49 +020065
66 // test_array
67 m.def("cast_array", []() { return std::array<int, 2> {{1 , 2}}; });
68 m.def("load_array", [](const std::array<int, 2> &a) { return a[0] == 1 && a[1] == 2; });
69
70 // test_valarray
71 m.def("cast_valarray", []() { return std::valarray<int>{1, 4, 9}; });
72 m.def("load_valarray", [](const std::valarray<int>& v) {
73 return v.size() == 3 && v[0] == 1 && v[1] == 4 && v[2] == 9;
74 });
75
76 // test_map
77 m.def("cast_map", []() { return std::map<std::string, std::string>{{"key", "value"}}; });
78 m.def("load_map", [](const std::map<std::string, std::string> &map) {
79 return map.at("key") == "value" && map.at("key2") == "value2";
80 });
81
82 // test_set
83 m.def("cast_set", []() { return std::set<std::string>{"key1", "key2"}; });
84 m.def("load_set", [](const std::set<std::string> &set) {
85 return set.count("key1") && set.count("key2") && set.count("key3");
86 });
87
Jason Rhinelanderb57281b2017-07-03 19:12:09 -040088 // test_recursive_casting
89 m.def("cast_rv_vector", []() { return std::vector<RValueCaster>{2}; });
90 m.def("cast_rv_array", []() { return std::array<RValueCaster, 3>(); });
91 // NB: map and set keys are `const`, so while we technically do move them (as `const Type &&`),
92 // casters don't typically do anything with that, which means they fall to the `const Type &`
93 // caster.
94 m.def("cast_rv_map", []() { return std::unordered_map<std::string, RValueCaster>{{"a", RValueCaster{}}}; });
95 m.def("cast_rv_nested", []() {
96 std::vector<std::array<std::list<std::unordered_map<std::string, RValueCaster>>, 2>> v;
97 v.emplace_back(); // add an array
98 v.back()[0].emplace_back(); // add a map to the array
99 v.back()[0].back().emplace("b", RValueCaster{});
100 v.back()[0].back().emplace("c", RValueCaster{});
101 v.back()[1].emplace_back(); // add a map to the array
102 v.back()[1].back().emplace("a", RValueCaster{});
103 return v;
104 });
Jason Rhinelanderb57281b2017-07-03 19:12:09 -0400105 static std::array<RValueCaster, 2> lva;
106 static std::unordered_map<std::string, RValueCaster> lvm{{"a", RValueCaster{}}, {"b", RValueCaster{}}};
107 static std::unordered_map<std::string, std::vector<std::list<std::array<RValueCaster, 2>>>> lvn;
108 lvn["a"].emplace_back(); // add a list
109 lvn["a"].back().emplace_back(); // add an array
110 lvn["a"].emplace_back(); // another list
111 lvn["a"].back().emplace_back(); // add an array
112 lvn["b"].emplace_back(); // add a list
113 lvn["b"].back().emplace_back(); // add an array
114 lvn["b"].back().emplace_back(); // add another array
115 m.def("cast_lv_vector", []() -> const decltype(lvv) & { return lvv; });
116 m.def("cast_lv_array", []() -> const decltype(lva) & { return lva; });
117 m.def("cast_lv_map", []() -> const decltype(lvm) & { return lvm; });
118 m.def("cast_lv_nested", []() -> const decltype(lvn) & { return lvn; });
119 // #853:
120 m.def("cast_unique_ptr_vector", []() {
121 std::vector<std::unique_ptr<UserType>> v;
122 v.emplace_back(new UserType{7});
123 v.emplace_back(new UserType{42});
124 return v;
125 });
126
Jason Rhinelander391c7542017-07-25 16:47:36 -0400127 // test_move_out_container
Dean Moldovan83e328f2017-06-09 00:44:49 +0200128 struct MoveOutContainer {
129 struct Value { int value; };
Dean Moldovan83e328f2017-06-09 00:44:49 +0200130 std::list<Value> move_list() const { return {{0}, {1}, {2}}; }
131 };
Dean Moldovan83e328f2017-06-09 00:44:49 +0200132 py::class_<MoveOutContainer::Value>(m, "MoveOutContainerValue")
133 .def_readonly("value", &MoveOutContainer::Value::value);
Dean Moldovan83e328f2017-06-09 00:44:49 +0200134 py::class_<MoveOutContainer>(m, "MoveOutContainer")
135 .def(py::init<>())
136 .def_property_readonly("move_list", &MoveOutContainer::move_list);
137
Jason Rhinelander391c7542017-07-25 16:47:36 -0400138 // Class that can be move- and copy-constructed, but not assigned
139 struct NoAssign {
140 int value;
141
142 explicit NoAssign(int value = 0) : value(value) { }
143 NoAssign(const NoAssign &) = default;
144 NoAssign(NoAssign &&) = default;
145
146 NoAssign &operator=(const NoAssign &) = delete;
147 NoAssign &operator=(NoAssign &&) = delete;
148 };
Dean Moldovan83e328f2017-06-09 00:44:49 +0200149 py::class_<NoAssign>(m, "NoAssign", "Class with no C++ assignment operators")
150 .def(py::init<>())
151 .def(py::init<int>());
152
153#ifdef PYBIND11_HAS_OPTIONAL
Jason Rhinelander391c7542017-07-25 16:47:36 -0400154 // test_optional
Dean Moldovan83e328f2017-06-09 00:44:49 +0200155 m.attr("has_optional") = true;
156
157 using opt_int = std::optional<int>;
158 using opt_no_assign = std::optional<NoAssign>;
159 m.def("double_or_zero", [](const opt_int& x) -> int {
160 return x.value_or(0) * 2;
161 });
162 m.def("half_or_none", [](int x) -> opt_int {
163 return x ? opt_int(x / 2) : opt_int();
164 });
165 m.def("test_nullopt", [](opt_int x) {
166 return x.value_or(42);
167 }, py::arg_v("x", std::nullopt, "None"));
168 m.def("test_no_assign", [](const opt_no_assign &x) {
169 return x ? x->value : 42;
170 }, py::arg_v("x", std::nullopt, "None"));
171
172 m.def("nodefer_none_optional", [](std::optional<int>) { return true; });
173 m.def("nodefer_none_optional", [](py::none) { return false; });
174#endif
175
176#ifdef PYBIND11_HAS_EXP_OPTIONAL
Jason Rhinelander391c7542017-07-25 16:47:36 -0400177 // test_exp_optional
Dean Moldovan83e328f2017-06-09 00:44:49 +0200178 m.attr("has_exp_optional") = true;
179
180 using exp_opt_int = std::experimental::optional<int>;
181 using exp_opt_no_assign = std::experimental::optional<NoAssign>;
182 m.def("double_or_zero_exp", [](const exp_opt_int& x) -> int {
183 return x.value_or(0) * 2;
184 });
185 m.def("half_or_none_exp", [](int x) -> exp_opt_int {
186 return x ? exp_opt_int(x / 2) : exp_opt_int();
187 });
188 m.def("test_nullopt_exp", [](exp_opt_int x) {
189 return x.value_or(42);
190 }, py::arg_v("x", std::experimental::nullopt, "None"));
191 m.def("test_no_assign_exp", [](const exp_opt_no_assign &x) {
192 return x ? x->value : 42;
193 }, py::arg_v("x", std::experimental::nullopt, "None"));
194#endif
195
196#ifdef PYBIND11_HAS_VARIANT
Dean Moldovan7918bcc2017-08-08 16:02:31 +0200197 static_assert(std::is_same<py::detail::variant_caster_visitor::result_type, py::handle>::value,
198 "visitor::result_type is required by boost::variant in C++11 mode");
199
Dean Moldovan83e328f2017-06-09 00:44:49 +0200200 struct visitor {
Dean Moldovan7918bcc2017-08-08 16:02:31 +0200201 using result_type = const char *;
202
203 result_type operator()(int) { return "int"; }
204 result_type operator()(std::string) { return "std::string"; }
205 result_type operator()(double) { return "double"; }
206 result_type operator()(std::nullptr_t) { return "std::nullptr_t"; }
Dean Moldovan83e328f2017-06-09 00:44:49 +0200207 };
208
Jason Rhinelander391c7542017-07-25 16:47:36 -0400209 // test_variant
Dean Moldovan7918bcc2017-08-08 16:02:31 +0200210 m.def("load_variant", [](variant<int, std::string, double, std::nullptr_t> v) {
211 return py::detail::visit_helper<variant>::call(visitor(), v);
Dean Moldovan83e328f2017-06-09 00:44:49 +0200212 });
Dean Moldovan7918bcc2017-08-08 16:02:31 +0200213 m.def("load_variant_2pass", [](variant<double, int> v) {
214 return py::detail::visit_helper<variant>::call(visitor(), v);
Dean Moldovan83e328f2017-06-09 00:44:49 +0200215 });
Dean Moldovan83e328f2017-06-09 00:44:49 +0200216 m.def("cast_variant", []() {
Dean Moldovan7918bcc2017-08-08 16:02:31 +0200217 using V = variant<int, std::string>;
Dean Moldovan83e328f2017-06-09 00:44:49 +0200218 return py::make_tuple(V(5), V("Hello"));
219 });
220#endif
221
Jason Rhinelander391c7542017-07-25 16:47:36 -0400222 // #528: templated constructor
223 // (no python tests: the test here is that this compiles)
Dean Moldovan83e328f2017-06-09 00:44:49 +0200224 m.def("tpl_ctor_vector", [](std::vector<TplCtorClass> &) {});
225 m.def("tpl_ctor_map", [](std::unordered_map<TplCtorClass, TplCtorClass> &) {});
226 m.def("tpl_ctor_set", [](std::unordered_set<TplCtorClass> &) {});
227#if defined(PYBIND11_HAS_OPTIONAL)
228 m.def("tpl_constr_optional", [](std::optional<TplCtorClass> &) {});
229#elif defined(PYBIND11_HAS_EXP_OPTIONAL)
230 m.def("tpl_constr_optional", [](std::experimental::optional<TplCtorClass> &) {});
231#endif
232
233 // test_vec_of_reference_wrapper
234 // #171: Can't return STL structures containing reference wrapper
235 m.def("return_vec_of_reference_wrapper", [](std::reference_wrapper<UserType> p4) {
236 static UserType p1{1}, p2{2}, p3{3};
237 return std::vector<std::reference_wrapper<UserType>> {
238 std::ref(p1), std::ref(p2), std::ref(p3), p4
239 };
240 });
241
Andreas Bergmeier34b7b542017-05-09 15:01:22 +0200242 // test_stl_pass_by_pointer
243 m.def("stl_pass_by_pointer", [](std::vector<int>* v) { return *v; }, "v"_a=nullptr);
Wenzel Jakobcbd16a82018-07-17 16:56:26 +0200244
Allan Leale76dff72018-10-11 10:28:12 +0200245 // #1258: pybind11/stl.h converts string to vector<string>
246 m.def("func_with_string_or_vector_string_arg_overload", [](std::vector<std::string>) { return 1; });
247 m.def("func_with_string_or_vector_string_arg_overload", [](std::list<std::string>) { return 2; });
248 m.def("func_with_string_or_vector_string_arg_overload", [](std::string) { return 3; });
249
Wenzel Jakobcbd16a82018-07-17 16:56:26 +0200250 class Placeholder {
251 public:
252 Placeholder() { print_created(this); }
253 Placeholder(const Placeholder &) = delete;
254 ~Placeholder() { print_destroyed(this); }
255 };
256 py::class_<Placeholder>(m, "Placeholder");
257
258 /// test_stl_vector_ownership
259 m.def("test_stl_ownership",
260 []() {
261 std::vector<Placeholder *> result;
262 result.push_back(new Placeholder());
263 return result;
264 },
265 py::return_value_policy::take_ownership);
Dean Moldovan83e328f2017-06-09 00:44:49 +0200266}