1/* 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 "constructor_stats.h" 12#include <pybind11/stl.h> 13 14#include <vector> 15#include <string> 16 17// Test with `std::variant` in C++17 mode, or with `boost::variant` in C++11/14 18#if PYBIND11_HAS_VARIANT 19using std::variant; 20#elif defined(PYBIND11_TEST_BOOST) && (!defined(_MSC_VER) || _MSC_VER >= 1910) 21# 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 38 39PYBIND11_MAKE_OPAQUE(std::vector<std::string, std::allocator<std::string>>); 40 41/// 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; }); 57 // `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 }); 62 // 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; }); 65 66 // 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 70 // 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 92 // 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 }); 109 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 131 // test_move_out_container 132 struct MoveOutContainer { 133 struct Value { int value; }; 134 std::list<Value> move_list() const { return {{0}, {1}, {2}}; } 135 }; 136 py::class_<MoveOutContainer::Value>(m, "MoveOutContainerValue") 137 .def_readonly("value", &MoveOutContainer::Value::value); 138 py::class_<MoveOutContainer>(m, "MoveOutContainer") 139 .def(py::init<>()) 140 .def_property_readonly("move_list", &MoveOutContainer::move_list); 141 142 // 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 }; 153 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 158 // test_optional 159 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 181 // test_exp_optional 182 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 201 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 204 struct visitor { 205 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"; } 211 }; 212 213 // test_variant 214 m.def("load_variant", [](variant<int, std::string, double, std::nullptr_t> v) { 215 return py::detail::visit_helper<variant>::call(visitor(), v); 216 }); 217 m.def("load_variant_2pass", [](variant<double, int> v) { 218 return py::detail::visit_helper<variant>::call(visitor(), v); 219 }); 220 m.def("cast_variant", []() { 221 using V = variant<int, std::string>; 222 return py::make_tuple(V(5), V("Hello")); 223 }); 224#endif 225 226 // #528: templated constructor 227 // (no python tests: the test here is that this compiles) 228 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 246 // test_stl_pass_by_pointer 247 m.def("stl_pass_by_pointer", [](std::vector<int>* v) { return *v; }, "v"_a=nullptr); 248 249 // #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 254 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); 270 271 m.def("array_cast_sequence", [](std::array<int, 3> x) { return x; }); 272 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); 284} 285