blob: 0746fb4d55da7ca9ffc43b848798c9cc2bdc875c [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"
11#include <pybind11/stl.h>
12
Dean Moldovan7918bcc2017-08-08 16:02:31 +020013// Test with `std::variant` in C++17 mode, or with `boost::variant` in C++11/14
14#if PYBIND11_HAS_VARIANT
15using std::variant;
Dean Moldovanc40ef612017-08-25 21:11:36 +020016#elif defined(PYBIND11_TEST_BOOST) && (!defined(_MSC_VER) || _MSC_VER >= 1910)
Dean Moldovan7918bcc2017-08-08 16:02:31 +020017# include <boost/variant.hpp>
18# define PYBIND11_HAS_VARIANT 1
19using boost::variant;
20
21namespace pybind11 { namespace detail {
22template <typename... Ts>
23struct type_caster<boost::variant<Ts...>> : variant_caster<boost::variant<Ts...>> {};
24
25template <>
26struct visit_helper<boost::variant> {
27 template <typename... Args>
28 static auto call(Args &&...args) -> decltype(boost::apply_visitor(args...)) {
29 return boost::apply_visitor(args...);
30 }
31};
32}} // namespace pybind11::detail
33#endif
Dean Moldovan83e328f2017-06-09 00:44:49 +020034
35/// Issue #528: templated constructor
36struct TplCtorClass {
37 template <typename T> TplCtorClass(const T &) { }
38 bool operator==(const TplCtorClass &) const { return true; }
39};
40
41namespace std {
42 template <>
43 struct hash<TplCtorClass> { size_t operator()(const TplCtorClass &) const { return 0; } };
44}
45
46
47TEST_SUBMODULE(stl, m) {
48 // test_vector
49 m.def("cast_vector", []() { return std::vector<int>{1}; });
50 m.def("load_vector", [](const std::vector<int> &v) { return v.at(0) == 1 && v.at(1) == 2; });
Jason Rhinelander67a0cc42017-07-06 20:41:52 -040051 // Unnumbered regression (caused by #936): pointers to stl containers aren't castable
52 static std::vector<RValueCaster> lvv{2};
53 m.def("cast_ptr_vector", []() { return &lvv; });
Dean Moldovan83e328f2017-06-09 00:44:49 +020054
55 // test_array
56 m.def("cast_array", []() { return std::array<int, 2> {{1 , 2}}; });
57 m.def("load_array", [](const std::array<int, 2> &a) { return a[0] == 1 && a[1] == 2; });
58
59 // test_valarray
60 m.def("cast_valarray", []() { return std::valarray<int>{1, 4, 9}; });
61 m.def("load_valarray", [](const std::valarray<int>& v) {
62 return v.size() == 3 && v[0] == 1 && v[1] == 4 && v[2] == 9;
63 });
64
65 // test_map
66 m.def("cast_map", []() { return std::map<std::string, std::string>{{"key", "value"}}; });
67 m.def("load_map", [](const std::map<std::string, std::string> &map) {
68 return map.at("key") == "value" && map.at("key2") == "value2";
69 });
70
71 // test_set
72 m.def("cast_set", []() { return std::set<std::string>{"key1", "key2"}; });
73 m.def("load_set", [](const std::set<std::string> &set) {
74 return set.count("key1") && set.count("key2") && set.count("key3");
75 });
76
Jason Rhinelanderb57281b2017-07-03 19:12:09 -040077 // test_recursive_casting
78 m.def("cast_rv_vector", []() { return std::vector<RValueCaster>{2}; });
79 m.def("cast_rv_array", []() { return std::array<RValueCaster, 3>(); });
80 // NB: map and set keys are `const`, so while we technically do move them (as `const Type &&`),
81 // casters don't typically do anything with that, which means they fall to the `const Type &`
82 // caster.
83 m.def("cast_rv_map", []() { return std::unordered_map<std::string, RValueCaster>{{"a", RValueCaster{}}}; });
84 m.def("cast_rv_nested", []() {
85 std::vector<std::array<std::list<std::unordered_map<std::string, RValueCaster>>, 2>> v;
86 v.emplace_back(); // add an array
87 v.back()[0].emplace_back(); // add a map to the array
88 v.back()[0].back().emplace("b", RValueCaster{});
89 v.back()[0].back().emplace("c", RValueCaster{});
90 v.back()[1].emplace_back(); // add a map to the array
91 v.back()[1].back().emplace("a", RValueCaster{});
92 return v;
93 });
Jason Rhinelanderb57281b2017-07-03 19:12:09 -040094 static std::array<RValueCaster, 2> lva;
95 static std::unordered_map<std::string, RValueCaster> lvm{{"a", RValueCaster{}}, {"b", RValueCaster{}}};
96 static std::unordered_map<std::string, std::vector<std::list<std::array<RValueCaster, 2>>>> lvn;
97 lvn["a"].emplace_back(); // add a list
98 lvn["a"].back().emplace_back(); // add an array
99 lvn["a"].emplace_back(); // another list
100 lvn["a"].back().emplace_back(); // add an array
101 lvn["b"].emplace_back(); // add a list
102 lvn["b"].back().emplace_back(); // add an array
103 lvn["b"].back().emplace_back(); // add another array
104 m.def("cast_lv_vector", []() -> const decltype(lvv) & { return lvv; });
105 m.def("cast_lv_array", []() -> const decltype(lva) & { return lva; });
106 m.def("cast_lv_map", []() -> const decltype(lvm) & { return lvm; });
107 m.def("cast_lv_nested", []() -> const decltype(lvn) & { return lvn; });
108 // #853:
109 m.def("cast_unique_ptr_vector", []() {
110 std::vector<std::unique_ptr<UserType>> v;
111 v.emplace_back(new UserType{7});
112 v.emplace_back(new UserType{42});
113 return v;
114 });
115
Jason Rhinelander391c7542017-07-25 16:47:36 -0400116 // test_move_out_container
Dean Moldovan83e328f2017-06-09 00:44:49 +0200117 struct MoveOutContainer {
118 struct Value { int value; };
Dean Moldovan83e328f2017-06-09 00:44:49 +0200119 std::list<Value> move_list() const { return {{0}, {1}, {2}}; }
120 };
Dean Moldovan83e328f2017-06-09 00:44:49 +0200121 py::class_<MoveOutContainer::Value>(m, "MoveOutContainerValue")
122 .def_readonly("value", &MoveOutContainer::Value::value);
Dean Moldovan83e328f2017-06-09 00:44:49 +0200123 py::class_<MoveOutContainer>(m, "MoveOutContainer")
124 .def(py::init<>())
125 .def_property_readonly("move_list", &MoveOutContainer::move_list);
126
Jason Rhinelander391c7542017-07-25 16:47:36 -0400127 // Class that can be move- and copy-constructed, but not assigned
128 struct NoAssign {
129 int value;
130
131 explicit NoAssign(int value = 0) : value(value) { }
132 NoAssign(const NoAssign &) = default;
133 NoAssign(NoAssign &&) = default;
134
135 NoAssign &operator=(const NoAssign &) = delete;
136 NoAssign &operator=(NoAssign &&) = delete;
137 };
Dean Moldovan83e328f2017-06-09 00:44:49 +0200138 py::class_<NoAssign>(m, "NoAssign", "Class with no C++ assignment operators")
139 .def(py::init<>())
140 .def(py::init<int>());
141
142#ifdef PYBIND11_HAS_OPTIONAL
Jason Rhinelander391c7542017-07-25 16:47:36 -0400143 // test_optional
Dean Moldovan83e328f2017-06-09 00:44:49 +0200144 m.attr("has_optional") = true;
145
146 using opt_int = std::optional<int>;
147 using opt_no_assign = std::optional<NoAssign>;
148 m.def("double_or_zero", [](const opt_int& x) -> int {
149 return x.value_or(0) * 2;
150 });
151 m.def("half_or_none", [](int x) -> opt_int {
152 return x ? opt_int(x / 2) : opt_int();
153 });
154 m.def("test_nullopt", [](opt_int x) {
155 return x.value_or(42);
156 }, py::arg_v("x", std::nullopt, "None"));
157 m.def("test_no_assign", [](const opt_no_assign &x) {
158 return x ? x->value : 42;
159 }, py::arg_v("x", std::nullopt, "None"));
160
161 m.def("nodefer_none_optional", [](std::optional<int>) { return true; });
162 m.def("nodefer_none_optional", [](py::none) { return false; });
163#endif
164
165#ifdef PYBIND11_HAS_EXP_OPTIONAL
Jason Rhinelander391c7542017-07-25 16:47:36 -0400166 // test_exp_optional
Dean Moldovan83e328f2017-06-09 00:44:49 +0200167 m.attr("has_exp_optional") = true;
168
169 using exp_opt_int = std::experimental::optional<int>;
170 using exp_opt_no_assign = std::experimental::optional<NoAssign>;
171 m.def("double_or_zero_exp", [](const exp_opt_int& x) -> int {
172 return x.value_or(0) * 2;
173 });
174 m.def("half_or_none_exp", [](int x) -> exp_opt_int {
175 return x ? exp_opt_int(x / 2) : exp_opt_int();
176 });
177 m.def("test_nullopt_exp", [](exp_opt_int x) {
178 return x.value_or(42);
179 }, py::arg_v("x", std::experimental::nullopt, "None"));
180 m.def("test_no_assign_exp", [](const exp_opt_no_assign &x) {
181 return x ? x->value : 42;
182 }, py::arg_v("x", std::experimental::nullopt, "None"));
183#endif
184
185#ifdef PYBIND11_HAS_VARIANT
Dean Moldovan7918bcc2017-08-08 16:02:31 +0200186 static_assert(std::is_same<py::detail::variant_caster_visitor::result_type, py::handle>::value,
187 "visitor::result_type is required by boost::variant in C++11 mode");
188
Dean Moldovan83e328f2017-06-09 00:44:49 +0200189 struct visitor {
Dean Moldovan7918bcc2017-08-08 16:02:31 +0200190 using result_type = const char *;
191
192 result_type operator()(int) { return "int"; }
193 result_type operator()(std::string) { return "std::string"; }
194 result_type operator()(double) { return "double"; }
195 result_type operator()(std::nullptr_t) { return "std::nullptr_t"; }
Dean Moldovan83e328f2017-06-09 00:44:49 +0200196 };
197
Jason Rhinelander391c7542017-07-25 16:47:36 -0400198 // test_variant
Dean Moldovan7918bcc2017-08-08 16:02:31 +0200199 m.def("load_variant", [](variant<int, std::string, double, std::nullptr_t> v) {
200 return py::detail::visit_helper<variant>::call(visitor(), v);
Dean Moldovan83e328f2017-06-09 00:44:49 +0200201 });
Dean Moldovan7918bcc2017-08-08 16:02:31 +0200202 m.def("load_variant_2pass", [](variant<double, int> v) {
203 return py::detail::visit_helper<variant>::call(visitor(), v);
Dean Moldovan83e328f2017-06-09 00:44:49 +0200204 });
Dean Moldovan83e328f2017-06-09 00:44:49 +0200205 m.def("cast_variant", []() {
Dean Moldovan7918bcc2017-08-08 16:02:31 +0200206 using V = variant<int, std::string>;
Dean Moldovan83e328f2017-06-09 00:44:49 +0200207 return py::make_tuple(V(5), V("Hello"));
208 });
209#endif
210
Jason Rhinelander391c7542017-07-25 16:47:36 -0400211 // #528: templated constructor
212 // (no python tests: the test here is that this compiles)
Dean Moldovan83e328f2017-06-09 00:44:49 +0200213 m.def("tpl_ctor_vector", [](std::vector<TplCtorClass> &) {});
214 m.def("tpl_ctor_map", [](std::unordered_map<TplCtorClass, TplCtorClass> &) {});
215 m.def("tpl_ctor_set", [](std::unordered_set<TplCtorClass> &) {});
216#if defined(PYBIND11_HAS_OPTIONAL)
217 m.def("tpl_constr_optional", [](std::optional<TplCtorClass> &) {});
218#elif defined(PYBIND11_HAS_EXP_OPTIONAL)
219 m.def("tpl_constr_optional", [](std::experimental::optional<TplCtorClass> &) {});
220#endif
221
222 // test_vec_of_reference_wrapper
223 // #171: Can't return STL structures containing reference wrapper
224 m.def("return_vec_of_reference_wrapper", [](std::reference_wrapper<UserType> p4) {
225 static UserType p1{1}, p2{2}, p3{3};
226 return std::vector<std::reference_wrapper<UserType>> {
227 std::ref(p1), std::ref(p2), std::ref(p3), p4
228 };
229 });
230
Andreas Bergmeier34b7b542017-05-09 15:01:22 +0200231 // test_stl_pass_by_pointer
232 m.def("stl_pass_by_pointer", [](std::vector<int>* v) { return *v; }, "v"_a=nullptr);
Dean Moldovan83e328f2017-06-09 00:44:49 +0200233}