blob: cd0985d02dcb25d06ab5a8a4ac561d5aeba9d5e5 [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
Dean Moldovan7918bcc2017-08-08 16:02:31 +020014// Test with `std::variant` in C++17 mode, or with `boost::variant` in C++11/14
15#if PYBIND11_HAS_VARIANT
16using std::variant;
Dean Moldovanc40ef612017-08-25 21:11:36 +020017#elif defined(PYBIND11_TEST_BOOST) && (!defined(_MSC_VER) || _MSC_VER >= 1910)
Dean Moldovan7918bcc2017-08-08 16:02:31 +020018# include <boost/variant.hpp>
19# define PYBIND11_HAS_VARIANT 1
20using boost::variant;
21
22namespace pybind11 { namespace detail {
23template <typename... Ts>
24struct type_caster<boost::variant<Ts...>> : variant_caster<boost::variant<Ts...>> {};
25
26template <>
27struct visit_helper<boost::variant> {
28 template <typename... Args>
29 static auto call(Args &&...args) -> decltype(boost::apply_visitor(args...)) {
30 return boost::apply_visitor(args...);
31 }
32};
33}} // namespace pybind11::detail
34#endif
Dean Moldovan83e328f2017-06-09 00:44:49 +020035
36/// Issue #528: templated constructor
37struct TplCtorClass {
38 template <typename T> TplCtorClass(const T &) { }
39 bool operator==(const TplCtorClass &) const { return true; }
40};
41
42namespace std {
43 template <>
44 struct hash<TplCtorClass> { size_t operator()(const TplCtorClass &) const { return 0; } };
45}
46
47
48TEST_SUBMODULE(stl, m) {
49 // test_vector
50 m.def("cast_vector", []() { return std::vector<int>{1}; });
51 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 +020052 // `std::vector<bool>` is special because it returns proxy objects instead of references
53 m.def("cast_bool_vector", []() { return std::vector<bool>{true, false}; });
54 m.def("load_bool_vector", [](const std::vector<bool> &v) {
55 return v.at(0) == true && v.at(1) == false;
56 });
Jason Rhinelander67a0cc42017-07-06 20:41:52 -040057 // Unnumbered regression (caused by #936): pointers to stl containers aren't castable
58 static std::vector<RValueCaster> lvv{2};
59 m.def("cast_ptr_vector", []() { return &lvv; });
Dean Moldovan83e328f2017-06-09 00:44:49 +020060
61 // test_array
62 m.def("cast_array", []() { return std::array<int, 2> {{1 , 2}}; });
63 m.def("load_array", [](const std::array<int, 2> &a) { return a[0] == 1 && a[1] == 2; });
64
65 // test_valarray
66 m.def("cast_valarray", []() { return std::valarray<int>{1, 4, 9}; });
67 m.def("load_valarray", [](const std::valarray<int>& v) {
68 return v.size() == 3 && v[0] == 1 && v[1] == 4 && v[2] == 9;
69 });
70
71 // test_map
72 m.def("cast_map", []() { return std::map<std::string, std::string>{{"key", "value"}}; });
73 m.def("load_map", [](const std::map<std::string, std::string> &map) {
74 return map.at("key") == "value" && map.at("key2") == "value2";
75 });
76
77 // test_set
78 m.def("cast_set", []() { return std::set<std::string>{"key1", "key2"}; });
79 m.def("load_set", [](const std::set<std::string> &set) {
80 return set.count("key1") && set.count("key2") && set.count("key3");
81 });
82
Jason Rhinelanderb57281b2017-07-03 19:12:09 -040083 // test_recursive_casting
84 m.def("cast_rv_vector", []() { return std::vector<RValueCaster>{2}; });
85 m.def("cast_rv_array", []() { return std::array<RValueCaster, 3>(); });
86 // NB: map and set keys are `const`, so while we technically do move them (as `const Type &&`),
87 // casters don't typically do anything with that, which means they fall to the `const Type &`
88 // caster.
89 m.def("cast_rv_map", []() { return std::unordered_map<std::string, RValueCaster>{{"a", RValueCaster{}}}; });
90 m.def("cast_rv_nested", []() {
91 std::vector<std::array<std::list<std::unordered_map<std::string, RValueCaster>>, 2>> v;
92 v.emplace_back(); // add an array
93 v.back()[0].emplace_back(); // add a map to the array
94 v.back()[0].back().emplace("b", RValueCaster{});
95 v.back()[0].back().emplace("c", RValueCaster{});
96 v.back()[1].emplace_back(); // add a map to the array
97 v.back()[1].back().emplace("a", RValueCaster{});
98 return v;
99 });
Jason Rhinelanderb57281b2017-07-03 19:12:09 -0400100 static std::array<RValueCaster, 2> lva;
101 static std::unordered_map<std::string, RValueCaster> lvm{{"a", RValueCaster{}}, {"b", RValueCaster{}}};
102 static std::unordered_map<std::string, std::vector<std::list<std::array<RValueCaster, 2>>>> lvn;
103 lvn["a"].emplace_back(); // add a list
104 lvn["a"].back().emplace_back(); // add an array
105 lvn["a"].emplace_back(); // another list
106 lvn["a"].back().emplace_back(); // add an array
107 lvn["b"].emplace_back(); // add a list
108 lvn["b"].back().emplace_back(); // add an array
109 lvn["b"].back().emplace_back(); // add another array
110 m.def("cast_lv_vector", []() -> const decltype(lvv) & { return lvv; });
111 m.def("cast_lv_array", []() -> const decltype(lva) & { return lva; });
112 m.def("cast_lv_map", []() -> const decltype(lvm) & { return lvm; });
113 m.def("cast_lv_nested", []() -> const decltype(lvn) & { return lvn; });
114 // #853:
115 m.def("cast_unique_ptr_vector", []() {
116 std::vector<std::unique_ptr<UserType>> v;
117 v.emplace_back(new UserType{7});
118 v.emplace_back(new UserType{42});
119 return v;
120 });
121
Jason Rhinelander391c7542017-07-25 16:47:36 -0400122 // test_move_out_container
Dean Moldovan83e328f2017-06-09 00:44:49 +0200123 struct MoveOutContainer {
124 struct Value { int value; };
Dean Moldovan83e328f2017-06-09 00:44:49 +0200125 std::list<Value> move_list() const { return {{0}, {1}, {2}}; }
126 };
Dean Moldovan83e328f2017-06-09 00:44:49 +0200127 py::class_<MoveOutContainer::Value>(m, "MoveOutContainerValue")
128 .def_readonly("value", &MoveOutContainer::Value::value);
Dean Moldovan83e328f2017-06-09 00:44:49 +0200129 py::class_<MoveOutContainer>(m, "MoveOutContainer")
130 .def(py::init<>())
131 .def_property_readonly("move_list", &MoveOutContainer::move_list);
132
Jason Rhinelander391c7542017-07-25 16:47:36 -0400133 // Class that can be move- and copy-constructed, but not assigned
134 struct NoAssign {
135 int value;
136
137 explicit NoAssign(int value = 0) : value(value) { }
138 NoAssign(const NoAssign &) = default;
139 NoAssign(NoAssign &&) = default;
140
141 NoAssign &operator=(const NoAssign &) = delete;
142 NoAssign &operator=(NoAssign &&) = delete;
143 };
Dean Moldovan83e328f2017-06-09 00:44:49 +0200144 py::class_<NoAssign>(m, "NoAssign", "Class with no C++ assignment operators")
145 .def(py::init<>())
146 .def(py::init<int>());
147
148#ifdef PYBIND11_HAS_OPTIONAL
Jason Rhinelander391c7542017-07-25 16:47:36 -0400149 // test_optional
Dean Moldovan83e328f2017-06-09 00:44:49 +0200150 m.attr("has_optional") = true;
151
152 using opt_int = std::optional<int>;
153 using opt_no_assign = std::optional<NoAssign>;
154 m.def("double_or_zero", [](const opt_int& x) -> int {
155 return x.value_or(0) * 2;
156 });
157 m.def("half_or_none", [](int x) -> opt_int {
158 return x ? opt_int(x / 2) : opt_int();
159 });
160 m.def("test_nullopt", [](opt_int x) {
161 return x.value_or(42);
162 }, py::arg_v("x", std::nullopt, "None"));
163 m.def("test_no_assign", [](const opt_no_assign &x) {
164 return x ? x->value : 42;
165 }, py::arg_v("x", std::nullopt, "None"));
166
167 m.def("nodefer_none_optional", [](std::optional<int>) { return true; });
168 m.def("nodefer_none_optional", [](py::none) { return false; });
169#endif
170
171#ifdef PYBIND11_HAS_EXP_OPTIONAL
Jason Rhinelander391c7542017-07-25 16:47:36 -0400172 // test_exp_optional
Dean Moldovan83e328f2017-06-09 00:44:49 +0200173 m.attr("has_exp_optional") = true;
174
175 using exp_opt_int = std::experimental::optional<int>;
176 using exp_opt_no_assign = std::experimental::optional<NoAssign>;
177 m.def("double_or_zero_exp", [](const exp_opt_int& x) -> int {
178 return x.value_or(0) * 2;
179 });
180 m.def("half_or_none_exp", [](int x) -> exp_opt_int {
181 return x ? exp_opt_int(x / 2) : exp_opt_int();
182 });
183 m.def("test_nullopt_exp", [](exp_opt_int x) {
184 return x.value_or(42);
185 }, py::arg_v("x", std::experimental::nullopt, "None"));
186 m.def("test_no_assign_exp", [](const exp_opt_no_assign &x) {
187 return x ? x->value : 42;
188 }, py::arg_v("x", std::experimental::nullopt, "None"));
189#endif
190
191#ifdef PYBIND11_HAS_VARIANT
Dean Moldovan7918bcc2017-08-08 16:02:31 +0200192 static_assert(std::is_same<py::detail::variant_caster_visitor::result_type, py::handle>::value,
193 "visitor::result_type is required by boost::variant in C++11 mode");
194
Dean Moldovan83e328f2017-06-09 00:44:49 +0200195 struct visitor {
Dean Moldovan7918bcc2017-08-08 16:02:31 +0200196 using result_type = const char *;
197
198 result_type operator()(int) { return "int"; }
199 result_type operator()(std::string) { return "std::string"; }
200 result_type operator()(double) { return "double"; }
201 result_type operator()(std::nullptr_t) { return "std::nullptr_t"; }
Dean Moldovan83e328f2017-06-09 00:44:49 +0200202 };
203
Jason Rhinelander391c7542017-07-25 16:47:36 -0400204 // test_variant
Dean Moldovan7918bcc2017-08-08 16:02:31 +0200205 m.def("load_variant", [](variant<int, std::string, double, std::nullptr_t> v) {
206 return py::detail::visit_helper<variant>::call(visitor(), v);
Dean Moldovan83e328f2017-06-09 00:44:49 +0200207 });
Dean Moldovan7918bcc2017-08-08 16:02:31 +0200208 m.def("load_variant_2pass", [](variant<double, int> v) {
209 return py::detail::visit_helper<variant>::call(visitor(), v);
Dean Moldovan83e328f2017-06-09 00:44:49 +0200210 });
Dean Moldovan83e328f2017-06-09 00:44:49 +0200211 m.def("cast_variant", []() {
Dean Moldovan7918bcc2017-08-08 16:02:31 +0200212 using V = variant<int, std::string>;
Dean Moldovan83e328f2017-06-09 00:44:49 +0200213 return py::make_tuple(V(5), V("Hello"));
214 });
215#endif
216
Jason Rhinelander391c7542017-07-25 16:47:36 -0400217 // #528: templated constructor
218 // (no python tests: the test here is that this compiles)
Dean Moldovan83e328f2017-06-09 00:44:49 +0200219 m.def("tpl_ctor_vector", [](std::vector<TplCtorClass> &) {});
220 m.def("tpl_ctor_map", [](std::unordered_map<TplCtorClass, TplCtorClass> &) {});
221 m.def("tpl_ctor_set", [](std::unordered_set<TplCtorClass> &) {});
222#if defined(PYBIND11_HAS_OPTIONAL)
223 m.def("tpl_constr_optional", [](std::optional<TplCtorClass> &) {});
224#elif defined(PYBIND11_HAS_EXP_OPTIONAL)
225 m.def("tpl_constr_optional", [](std::experimental::optional<TplCtorClass> &) {});
226#endif
227
228 // test_vec_of_reference_wrapper
229 // #171: Can't return STL structures containing reference wrapper
230 m.def("return_vec_of_reference_wrapper", [](std::reference_wrapper<UserType> p4) {
231 static UserType p1{1}, p2{2}, p3{3};
232 return std::vector<std::reference_wrapper<UserType>> {
233 std::ref(p1), std::ref(p2), std::ref(p3), p4
234 };
235 });
236
Andreas Bergmeier34b7b542017-05-09 15:01:22 +0200237 // test_stl_pass_by_pointer
238 m.def("stl_pass_by_pointer", [](std::vector<int>* v) { return *v; }, "v"_a=nullptr);
Wenzel Jakobcbd16a82018-07-17 16:56:26 +0200239
240 class Placeholder {
241 public:
242 Placeholder() { print_created(this); }
243 Placeholder(const Placeholder &) = delete;
244 ~Placeholder() { print_destroyed(this); }
245 };
246 py::class_<Placeholder>(m, "Placeholder");
247
248 /// test_stl_vector_ownership
249 m.def("test_stl_ownership",
250 []() {
251 std::vector<Placeholder *> result;
252 result.push_back(new Placeholder());
253 return result;
254 },
255 py::return_value_policy::take_ownership);
Dean Moldovan83e328f2017-06-09 00:44:49 +0200256}