blob: 207c9fb2bf8749e902ed8a30836ff0b73d826f42 [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
voxmea17983e72018-11-16 00:45:19 -050066 // test_deque
67 m.def("cast_deque", []() { return std::deque<int>{1}; });
68 m.def("load_deque", [](const std::deque<int> &v) { return v.at(0) == 1 && v.at(1) == 2; });
69
Dean Moldovan83e328f2017-06-09 00:44:49 +020070 // test_array
71 m.def("cast_array", []() { return std::array<int, 2> {{1 , 2}}; });
72 m.def("load_array", [](const std::array<int, 2> &a) { return a[0] == 1 && a[1] == 2; });
73
74 // test_valarray
75 m.def("cast_valarray", []() { return std::valarray<int>{1, 4, 9}; });
76 m.def("load_valarray", [](const std::valarray<int>& v) {
77 return v.size() == 3 && v[0] == 1 && v[1] == 4 && v[2] == 9;
78 });
79
80 // test_map
81 m.def("cast_map", []() { return std::map<std::string, std::string>{{"key", "value"}}; });
82 m.def("load_map", [](const std::map<std::string, std::string> &map) {
83 return map.at("key") == "value" && map.at("key2") == "value2";
84 });
85
86 // test_set
87 m.def("cast_set", []() { return std::set<std::string>{"key1", "key2"}; });
88 m.def("load_set", [](const std::set<std::string> &set) {
89 return set.count("key1") && set.count("key2") && set.count("key3");
90 });
91
Jason Rhinelanderb57281b2017-07-03 19:12:09 -040092 // test_recursive_casting
93 m.def("cast_rv_vector", []() { return std::vector<RValueCaster>{2}; });
94 m.def("cast_rv_array", []() { return std::array<RValueCaster, 3>(); });
95 // NB: map and set keys are `const`, so while we technically do move them (as `const Type &&`),
96 // casters don't typically do anything with that, which means they fall to the `const Type &`
97 // caster.
98 m.def("cast_rv_map", []() { return std::unordered_map<std::string, RValueCaster>{{"a", RValueCaster{}}}; });
99 m.def("cast_rv_nested", []() {
100 std::vector<std::array<std::list<std::unordered_map<std::string, RValueCaster>>, 2>> v;
101 v.emplace_back(); // add an array
102 v.back()[0].emplace_back(); // add a map to the array
103 v.back()[0].back().emplace("b", RValueCaster{});
104 v.back()[0].back().emplace("c", RValueCaster{});
105 v.back()[1].emplace_back(); // add a map to the array
106 v.back()[1].back().emplace("a", RValueCaster{});
107 return v;
108 });
Jason Rhinelanderb57281b2017-07-03 19:12:09 -0400109 static std::array<RValueCaster, 2> lva;
110 static std::unordered_map<std::string, RValueCaster> lvm{{"a", RValueCaster{}}, {"b", RValueCaster{}}};
111 static std::unordered_map<std::string, std::vector<std::list<std::array<RValueCaster, 2>>>> lvn;
112 lvn["a"].emplace_back(); // add a list
113 lvn["a"].back().emplace_back(); // add an array
114 lvn["a"].emplace_back(); // another list
115 lvn["a"].back().emplace_back(); // add an array
116 lvn["b"].emplace_back(); // add a list
117 lvn["b"].back().emplace_back(); // add an array
118 lvn["b"].back().emplace_back(); // add another array
119 m.def("cast_lv_vector", []() -> const decltype(lvv) & { return lvv; });
120 m.def("cast_lv_array", []() -> const decltype(lva) & { return lva; });
121 m.def("cast_lv_map", []() -> const decltype(lvm) & { return lvm; });
122 m.def("cast_lv_nested", []() -> const decltype(lvn) & { return lvn; });
123 // #853:
124 m.def("cast_unique_ptr_vector", []() {
125 std::vector<std::unique_ptr<UserType>> v;
126 v.emplace_back(new UserType{7});
127 v.emplace_back(new UserType{42});
128 return v;
129 });
130
Jason Rhinelander391c7542017-07-25 16:47:36 -0400131 // test_move_out_container
Dean Moldovan83e328f2017-06-09 00:44:49 +0200132 struct MoveOutContainer {
133 struct Value { int value; };
Dean Moldovan83e328f2017-06-09 00:44:49 +0200134 std::list<Value> move_list() const { return {{0}, {1}, {2}}; }
135 };
Dean Moldovan83e328f2017-06-09 00:44:49 +0200136 py::class_<MoveOutContainer::Value>(m, "MoveOutContainerValue")
137 .def_readonly("value", &MoveOutContainer::Value::value);
Dean Moldovan83e328f2017-06-09 00:44:49 +0200138 py::class_<MoveOutContainer>(m, "MoveOutContainer")
139 .def(py::init<>())
140 .def_property_readonly("move_list", &MoveOutContainer::move_list);
141
Jason Rhinelander391c7542017-07-25 16:47:36 -0400142 // Class that can be move- and copy-constructed, but not assigned
143 struct NoAssign {
144 int value;
145
146 explicit NoAssign(int value = 0) : value(value) { }
147 NoAssign(const NoAssign &) = default;
148 NoAssign(NoAssign &&) = default;
149
150 NoAssign &operator=(const NoAssign &) = delete;
151 NoAssign &operator=(NoAssign &&) = delete;
152 };
Dean Moldovan83e328f2017-06-09 00:44:49 +0200153 py::class_<NoAssign>(m, "NoAssign", "Class with no C++ assignment operators")
154 .def(py::init<>())
155 .def(py::init<int>());
156
157#ifdef PYBIND11_HAS_OPTIONAL
Jason Rhinelander391c7542017-07-25 16:47:36 -0400158 // test_optional
Dean Moldovan83e328f2017-06-09 00:44:49 +0200159 m.attr("has_optional") = true;
160
161 using opt_int = std::optional<int>;
162 using opt_no_assign = std::optional<NoAssign>;
163 m.def("double_or_zero", [](const opt_int& x) -> int {
164 return x.value_or(0) * 2;
165 });
166 m.def("half_or_none", [](int x) -> opt_int {
167 return x ? opt_int(x / 2) : opt_int();
168 });
169 m.def("test_nullopt", [](opt_int x) {
170 return x.value_or(42);
171 }, py::arg_v("x", std::nullopt, "None"));
172 m.def("test_no_assign", [](const opt_no_assign &x) {
173 return x ? x->value : 42;
174 }, py::arg_v("x", std::nullopt, "None"));
175
176 m.def("nodefer_none_optional", [](std::optional<int>) { return true; });
177 m.def("nodefer_none_optional", [](py::none) { return false; });
178#endif
179
180#ifdef PYBIND11_HAS_EXP_OPTIONAL
Jason Rhinelander391c7542017-07-25 16:47:36 -0400181 // test_exp_optional
Dean Moldovan83e328f2017-06-09 00:44:49 +0200182 m.attr("has_exp_optional") = true;
183
184 using exp_opt_int = std::experimental::optional<int>;
185 using exp_opt_no_assign = std::experimental::optional<NoAssign>;
186 m.def("double_or_zero_exp", [](const exp_opt_int& x) -> int {
187 return x.value_or(0) * 2;
188 });
189 m.def("half_or_none_exp", [](int x) -> exp_opt_int {
190 return x ? exp_opt_int(x / 2) : exp_opt_int();
191 });
192 m.def("test_nullopt_exp", [](exp_opt_int x) {
193 return x.value_or(42);
194 }, py::arg_v("x", std::experimental::nullopt, "None"));
195 m.def("test_no_assign_exp", [](const exp_opt_no_assign &x) {
196 return x ? x->value : 42;
197 }, py::arg_v("x", std::experimental::nullopt, "None"));
198#endif
199
200#ifdef PYBIND11_HAS_VARIANT
Dean Moldovan7918bcc2017-08-08 16:02:31 +0200201 static_assert(std::is_same<py::detail::variant_caster_visitor::result_type, py::handle>::value,
202 "visitor::result_type is required by boost::variant in C++11 mode");
203
Dean Moldovan83e328f2017-06-09 00:44:49 +0200204 struct visitor {
Dean Moldovan7918bcc2017-08-08 16:02:31 +0200205 using result_type = const char *;
206
207 result_type operator()(int) { return "int"; }
208 result_type operator()(std::string) { return "std::string"; }
209 result_type operator()(double) { return "double"; }
210 result_type operator()(std::nullptr_t) { return "std::nullptr_t"; }
Dean Moldovan83e328f2017-06-09 00:44:49 +0200211 };
212
Jason Rhinelander391c7542017-07-25 16:47:36 -0400213 // test_variant
Dean Moldovan7918bcc2017-08-08 16:02:31 +0200214 m.def("load_variant", [](variant<int, std::string, double, std::nullptr_t> v) {
215 return py::detail::visit_helper<variant>::call(visitor(), v);
Dean Moldovan83e328f2017-06-09 00:44:49 +0200216 });
Dean Moldovan7918bcc2017-08-08 16:02:31 +0200217 m.def("load_variant_2pass", [](variant<double, int> v) {
218 return py::detail::visit_helper<variant>::call(visitor(), v);
Dean Moldovan83e328f2017-06-09 00:44:49 +0200219 });
Dean Moldovan83e328f2017-06-09 00:44:49 +0200220 m.def("cast_variant", []() {
Dean Moldovan7918bcc2017-08-08 16:02:31 +0200221 using V = variant<int, std::string>;
Dean Moldovan83e328f2017-06-09 00:44:49 +0200222 return py::make_tuple(V(5), V("Hello"));
223 });
224#endif
225
Jason Rhinelander391c7542017-07-25 16:47:36 -0400226 // #528: templated constructor
227 // (no python tests: the test here is that this compiles)
Dean Moldovan83e328f2017-06-09 00:44:49 +0200228 m.def("tpl_ctor_vector", [](std::vector<TplCtorClass> &) {});
229 m.def("tpl_ctor_map", [](std::unordered_map<TplCtorClass, TplCtorClass> &) {});
230 m.def("tpl_ctor_set", [](std::unordered_set<TplCtorClass> &) {});
231#if defined(PYBIND11_HAS_OPTIONAL)
232 m.def("tpl_constr_optional", [](std::optional<TplCtorClass> &) {});
233#elif defined(PYBIND11_HAS_EXP_OPTIONAL)
234 m.def("tpl_constr_optional", [](std::experimental::optional<TplCtorClass> &) {});
235#endif
236
237 // test_vec_of_reference_wrapper
238 // #171: Can't return STL structures containing reference wrapper
239 m.def("return_vec_of_reference_wrapper", [](std::reference_wrapper<UserType> p4) {
240 static UserType p1{1}, p2{2}, p3{3};
241 return std::vector<std::reference_wrapper<UserType>> {
242 std::ref(p1), std::ref(p2), std::ref(p3), p4
243 };
244 });
245
Andreas Bergmeier34b7b542017-05-09 15:01:22 +0200246 // test_stl_pass_by_pointer
247 m.def("stl_pass_by_pointer", [](std::vector<int>* v) { return *v; }, "v"_a=nullptr);
Wenzel Jakobcbd16a82018-07-17 16:56:26 +0200248
Allan Leale76dff72018-10-11 10:28:12 +0200249 // #1258: pybind11/stl.h converts string to vector<string>
250 m.def("func_with_string_or_vector_string_arg_overload", [](std::vector<std::string>) { return 1; });
251 m.def("func_with_string_or_vector_string_arg_overload", [](std::list<std::string>) { return 2; });
252 m.def("func_with_string_or_vector_string_arg_overload", [](std::string) { return 3; });
253
Wenzel Jakobcbd16a82018-07-17 16:56:26 +0200254 class Placeholder {
255 public:
256 Placeholder() { print_created(this); }
257 Placeholder(const Placeholder &) = delete;
258 ~Placeholder() { print_destroyed(this); }
259 };
260 py::class_<Placeholder>(m, "Placeholder");
261
262 /// test_stl_vector_ownership
263 m.def("test_stl_ownership",
264 []() {
265 std::vector<Placeholder *> result;
266 result.push_back(new Placeholder());
267 return result;
268 },
269 py::return_value_policy::take_ownership);
Wenzel Jakob9f730602018-11-09 12:32:48 +0100270
271 m.def("array_cast_sequence", [](std::array<int, 3> x) { return x; });
Wenzel Jakobadc2cdd2018-11-09 20:12:46 +0100272
273 /// test_issue_1561
274 struct Issue1561Inner { std::string data; };
275 struct Issue1561Outer { std::vector<Issue1561Inner> list; };
276
277 py::class_<Issue1561Inner>(m, "Issue1561Inner")
278 .def(py::init<std::string>())
279 .def_readwrite("data", &Issue1561Inner::data);
280
281 py::class_<Issue1561Outer>(m, "Issue1561Outer")
282 .def(py::init<>())
283 .def_readwrite("list", &Issue1561Outer::list);
Dean Moldovan83e328f2017-06-09 00:44:49 +0200284}