test_stl.cpp revision 12391:ceeca8b41e4b
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 <pybind11/stl.h>
12
13// Test with `std::variant` in C++17 mode, or with `boost::variant` in C++11/14
14#if PYBIND11_HAS_VARIANT
15using std::variant;
16#elif defined(PYBIND11_TEST_BOOST) && (!defined(_MSC_VER) || _MSC_VER >= 1910)
17#  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
34
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; });
51    // `std::vector<bool>` is special because it returns proxy objects instead of references
52    m.def("cast_bool_vector", []() { return std::vector<bool>{true, false}; });
53    m.def("load_bool_vector", [](const std::vector<bool> &v) {
54        return v.at(0) == true && v.at(1) == false;
55    });
56    // Unnumbered regression (caused by #936): pointers to stl containers aren't castable
57    static std::vector<RValueCaster> lvv{2};
58    m.def("cast_ptr_vector", []() { return &lvv; });
59
60    // test_array
61    m.def("cast_array", []() { return std::array<int, 2> {{1 , 2}}; });
62    m.def("load_array", [](const std::array<int, 2> &a) { return a[0] == 1 && a[1] == 2; });
63
64    // test_valarray
65    m.def("cast_valarray", []() { return std::valarray<int>{1, 4, 9}; });
66    m.def("load_valarray", [](const std::valarray<int>& v) {
67        return v.size() == 3 && v[0] == 1 && v[1] == 4 && v[2] == 9;
68    });
69
70    // test_map
71    m.def("cast_map", []() { return std::map<std::string, std::string>{{"key", "value"}}; });
72    m.def("load_map", [](const std::map<std::string, std::string> &map) {
73        return map.at("key") == "value" && map.at("key2") == "value2";
74    });
75
76    // test_set
77    m.def("cast_set", []() { return std::set<std::string>{"key1", "key2"}; });
78    m.def("load_set", [](const std::set<std::string> &set) {
79        return set.count("key1") && set.count("key2") && set.count("key3");
80    });
81
82    // test_recursive_casting
83    m.def("cast_rv_vector", []() { return std::vector<RValueCaster>{2}; });
84    m.def("cast_rv_array", []() { return std::array<RValueCaster, 3>(); });
85    // NB: map and set keys are `const`, so while we technically do move them (as `const Type &&`),
86    // casters don't typically do anything with that, which means they fall to the `const Type &`
87    // caster.
88    m.def("cast_rv_map", []() { return std::unordered_map<std::string, RValueCaster>{{"a", RValueCaster{}}}; });
89    m.def("cast_rv_nested", []() {
90        std::vector<std::array<std::list<std::unordered_map<std::string, RValueCaster>>, 2>> v;
91        v.emplace_back(); // add an array
92        v.back()[0].emplace_back(); // add a map to the array
93        v.back()[0].back().emplace("b", RValueCaster{});
94        v.back()[0].back().emplace("c", RValueCaster{});
95        v.back()[1].emplace_back(); // add a map to the array
96        v.back()[1].back().emplace("a", RValueCaster{});
97        return v;
98    });
99    static std::array<RValueCaster, 2> lva;
100    static std::unordered_map<std::string, RValueCaster> lvm{{"a", RValueCaster{}}, {"b", RValueCaster{}}};
101    static std::unordered_map<std::string, std::vector<std::list<std::array<RValueCaster, 2>>>> lvn;
102    lvn["a"].emplace_back(); // add a list
103    lvn["a"].back().emplace_back(); // add an array
104    lvn["a"].emplace_back(); // another list
105    lvn["a"].back().emplace_back(); // add an array
106    lvn["b"].emplace_back(); // add a list
107    lvn["b"].back().emplace_back(); // add an array
108    lvn["b"].back().emplace_back(); // add another array
109    m.def("cast_lv_vector", []() -> const decltype(lvv) & { return lvv; });
110    m.def("cast_lv_array", []() -> const decltype(lva) & { return lva; });
111    m.def("cast_lv_map", []() -> const decltype(lvm) & { return lvm; });
112    m.def("cast_lv_nested", []() -> const decltype(lvn) & { return lvn; });
113    // #853:
114    m.def("cast_unique_ptr_vector", []() {
115        std::vector<std::unique_ptr<UserType>> v;
116        v.emplace_back(new UserType{7});
117        v.emplace_back(new UserType{42});
118        return v;
119    });
120
121    // test_move_out_container
122    struct MoveOutContainer {
123        struct Value { int value; };
124        std::list<Value> move_list() const { return {{0}, {1}, {2}}; }
125    };
126    py::class_<MoveOutContainer::Value>(m, "MoveOutContainerValue")
127        .def_readonly("value", &MoveOutContainer::Value::value);
128    py::class_<MoveOutContainer>(m, "MoveOutContainer")
129        .def(py::init<>())
130        .def_property_readonly("move_list", &MoveOutContainer::move_list);
131
132    // Class that can be move- and copy-constructed, but not assigned
133    struct NoAssign {
134        int value;
135
136        explicit NoAssign(int value = 0) : value(value) { }
137        NoAssign(const NoAssign &) = default;
138        NoAssign(NoAssign &&) = default;
139
140        NoAssign &operator=(const NoAssign &) = delete;
141        NoAssign &operator=(NoAssign &&) = delete;
142    };
143    py::class_<NoAssign>(m, "NoAssign", "Class with no C++ assignment operators")
144        .def(py::init<>())
145        .def(py::init<int>());
146
147#ifdef PYBIND11_HAS_OPTIONAL
148    // test_optional
149    m.attr("has_optional") = true;
150
151    using opt_int = std::optional<int>;
152    using opt_no_assign = std::optional<NoAssign>;
153    m.def("double_or_zero", [](const opt_int& x) -> int {
154        return x.value_or(0) * 2;
155    });
156    m.def("half_or_none", [](int x) -> opt_int {
157        return x ? opt_int(x / 2) : opt_int();
158    });
159    m.def("test_nullopt", [](opt_int x) {
160        return x.value_or(42);
161    }, py::arg_v("x", std::nullopt, "None"));
162    m.def("test_no_assign", [](const opt_no_assign &x) {
163        return x ? x->value : 42;
164    }, py::arg_v("x", std::nullopt, "None"));
165
166    m.def("nodefer_none_optional", [](std::optional<int>) { return true; });
167    m.def("nodefer_none_optional", [](py::none) { return false; });
168#endif
169
170#ifdef PYBIND11_HAS_EXP_OPTIONAL
171    // test_exp_optional
172    m.attr("has_exp_optional") = true;
173
174    using exp_opt_int = std::experimental::optional<int>;
175    using exp_opt_no_assign = std::experimental::optional<NoAssign>;
176    m.def("double_or_zero_exp", [](const exp_opt_int& x) -> int {
177        return x.value_or(0) * 2;
178    });
179    m.def("half_or_none_exp", [](int x) -> exp_opt_int {
180        return x ? exp_opt_int(x / 2) : exp_opt_int();
181    });
182    m.def("test_nullopt_exp", [](exp_opt_int x) {
183        return x.value_or(42);
184    }, py::arg_v("x", std::experimental::nullopt, "None"));
185    m.def("test_no_assign_exp", [](const exp_opt_no_assign &x) {
186        return x ? x->value : 42;
187    }, py::arg_v("x", std::experimental::nullopt, "None"));
188#endif
189
190#ifdef PYBIND11_HAS_VARIANT
191    static_assert(std::is_same<py::detail::variant_caster_visitor::result_type, py::handle>::value,
192                  "visitor::result_type is required by boost::variant in C++11 mode");
193
194    struct visitor {
195        using result_type = const char *;
196
197        result_type operator()(int) { return "int"; }
198        result_type operator()(std::string) { return "std::string"; }
199        result_type operator()(double) { return "double"; }
200        result_type operator()(std::nullptr_t) { return "std::nullptr_t"; }
201    };
202
203    // test_variant
204    m.def("load_variant", [](variant<int, std::string, double, std::nullptr_t> v) {
205        return py::detail::visit_helper<variant>::call(visitor(), v);
206    });
207    m.def("load_variant_2pass", [](variant<double, int> v) {
208        return py::detail::visit_helper<variant>::call(visitor(), v);
209    });
210    m.def("cast_variant", []() {
211        using V = variant<int, std::string>;
212        return py::make_tuple(V(5), V("Hello"));
213    });
214#endif
215
216    // #528: templated constructor
217    // (no python tests: the test here is that this compiles)
218    m.def("tpl_ctor_vector", [](std::vector<TplCtorClass> &) {});
219    m.def("tpl_ctor_map", [](std::unordered_map<TplCtorClass, TplCtorClass> &) {});
220    m.def("tpl_ctor_set", [](std::unordered_set<TplCtorClass> &) {});
221#if defined(PYBIND11_HAS_OPTIONAL)
222    m.def("tpl_constr_optional", [](std::optional<TplCtorClass> &) {});
223#elif defined(PYBIND11_HAS_EXP_OPTIONAL)
224    m.def("tpl_constr_optional", [](std::experimental::optional<TplCtorClass> &) {});
225#endif
226
227    // test_vec_of_reference_wrapper
228    // #171: Can't return STL structures containing reference wrapper
229    m.def("return_vec_of_reference_wrapper", [](std::reference_wrapper<UserType> p4) {
230        static UserType p1{1}, p2{2}, p3{3};
231        return std::vector<std::reference_wrapper<UserType>> {
232            std::ref(p1), std::ref(p2), std::ref(p3), p4
233        };
234    });
235
236    // test_stl_pass_by_pointer
237    m.def("stl_pass_by_pointer", [](std::vector<int>* v) { return *v; }, "v"_a=nullptr);
238}
239