Deleted Added
sdiff udiff text old ( 11986:c12e4625ab56 ) new ( 12037:d28054ac6ec9 )
full compact
1/*
2 tests/test_stl_binders.cpp -- Usage of stl_binders functions
3
4 Copyright (c) 2016 Sergey Lyskov
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
12#include <pybind11/stl_bind.h>
13#include <map>
14#include <deque>
15#include <unordered_map>
16
17class El {
18public:
19 El() = delete;
20 El(int v) : a(v) { }
21
22 int a;
23};
24
25std::ostream & operator<<(std::ostream &s, El const&v) {
26 s << "El{" << v.a << '}';
27 return s;
28}
29
30/// Issue #487: binding std::vector<E> with E non-copyable
31class E_nc {
32public:
33 explicit E_nc(int i) : value{i} {}
34 E_nc(const E_nc &) = delete;
35 E_nc &operator=(const E_nc &) = delete;
36 E_nc(E_nc &&) = default;
37 E_nc &operator=(E_nc &&) = default;
38
39 int value;
40};
41
42template <class Container> Container *one_to_n(int n) {
43 auto v = new Container();
44 for (int i = 1; i <= n; i++)
45 v->emplace_back(i);
46 return v;
47}
48
49template <class Map> Map *times_ten(int n) {
50 auto m = new Map();
51 for (int i = 1; i <= n; i++)
52 m->emplace(int(i), E_nc(10*i));
53 return m;
54}
55
56test_initializer stl_binder_vector([](py::module &m) {
57 py::class_<El>(m, "El")
58 .def(py::init<int>());
59
60 py::bind_vector<std::vector<unsigned int>>(m, "VectorInt");
61 py::bind_vector<std::vector<bool>>(m, "VectorBool");
62
63 py::bind_vector<std::vector<El>>(m, "VectorEl");
64
65 py::bind_vector<std::vector<std::vector<El>>>(m, "VectorVectorEl");
66
67});
68
69test_initializer stl_binder_map([](py::module &m) {
70 py::bind_map<std::map<std::string, double>>(m, "MapStringDouble");
71 py::bind_map<std::unordered_map<std::string, double>>(m, "UnorderedMapStringDouble");
72
73 py::bind_map<std::map<std::string, double const>>(m, "MapStringDoubleConst");
74 py::bind_map<std::unordered_map<std::string, double const>>(m, "UnorderedMapStringDoubleConst");
75
76});
77
78test_initializer stl_binder_noncopyable([](py::module &m) {
79 py::class_<E_nc>(m, "ENC")
80 .def(py::init<int>())
81 .def_readwrite("value", &E_nc::value);
82
83 py::bind_vector<std::vector<E_nc>>(m, "VectorENC");
84 m.def("get_vnc", &one_to_n<std::vector<E_nc>>, py::return_value_policy::reference);
85
86 py::bind_vector<std::deque<E_nc>>(m, "DequeENC");
87 m.def("get_dnc", &one_to_n<std::deque<E_nc>>, py::return_value_policy::reference);
88
89 py::bind_map<std::map<int, E_nc>>(m, "MapENC");
90 m.def("get_mnc", &times_ten<std::map<int, E_nc>>, py::return_value_policy::reference);
91
92 py::bind_map<std::unordered_map<int, E_nc>>(m, "UmapENC");
93 m.def("get_umnc", &times_ten<std::unordered_map<int, E_nc>>, py::return_value_policy::reference);
94});
95