@@ -192,34 +192,41 @@ void init_issues(py::module &m) {
192
192
m2.def (" get_moveissue1" , [](int i) -> MoveIssue1 * { return new MoveIssue1 (i); }, py::return_value_policy::move);
193
193
m2.def (" get_moveissue2" , [](int i) { return MoveIssue2 (i); }, py::return_value_policy::move);
194
194
195
- // Issue 392: overridding reference-returning functions
195
+ // Issues 392/397 : overridding reference-returning functions
196
196
class OverrideTest {
197
197
public:
198
- struct A { int value = 99 ; };
199
- int v;
198
+ struct A { std::string value = " hi " ; };
199
+ std::string v;
200
200
A a;
201
- explicit OverrideTest (int v) : v{v} {}
202
- virtual int int_value () { return v; }
203
- virtual int & int_ref () { return v; }
201
+ explicit OverrideTest (const std::string & v) : v{v} {}
202
+ virtual std::string str_value () { return v; }
203
+ virtual std::string & str_ref () { return v; }
204
204
virtual A A_value () { return a; }
205
205
virtual A &A_ref () { return a; }
206
206
};
207
207
class PyOverrideTest : public OverrideTest {
208
208
public:
209
209
using OverrideTest::OverrideTest;
210
- int int_value () override { PYBIND11_OVERLOAD (int , OverrideTest, int_value ); }
210
+ std::string str_value () override { PYBIND11_OVERLOAD (std::string , OverrideTest, str_value ); }
211
211
// Not allowed (uncommenting should hit a static_assert failure): we can't get a reference
212
212
// to a python numeric value, since we only copy values in the numeric type caster:
213
- // int &int_ref() override { PYBIND11_OVERLOAD(int &, OverrideTest, int_ref); }
213
+ // std::string &str_ref() override { PYBIND11_OVERLOAD(std::string &, OverrideTest, str_ref); }
214
+ // But we can work around it like this:
215
+ private:
216
+ std::string _tmp;
217
+ std::string str_ref_helper () { PYBIND11_OVERLOAD (std::string, OverrideTest, str_ref); }
218
+ public:
219
+ std::string &str_ref () override { return _tmp = str_ref_helper (); }
220
+
214
221
A A_value () override { PYBIND11_OVERLOAD (A, OverrideTest, A_value); }
215
222
A &A_ref () override { PYBIND11_OVERLOAD (A &, OverrideTest, A_ref); }
216
223
};
217
224
py::class_<OverrideTest::A>(m2, " OverrideTest_A" )
218
225
.def_readwrite (" value" , &OverrideTest::A::value);
219
226
py::class_<OverrideTest, PyOverrideTest>(m2, " OverrideTest" )
220
- .def (py::init<int >())
221
- .def (" int_value " , &OverrideTest::int_value )
222
- // .def("int_ref ", &OverrideTest::int_ref )
227
+ .def (py::init<const std::string & >())
228
+ .def (" str_value " , &OverrideTest::str_value )
229
+ // .def("str_ref ", &OverrideTest::str_ref )
223
230
.def (" A_value" , &OverrideTest::A_value)
224
231
.def (" A_ref" , &OverrideTest::A_ref);
225
232
0 commit comments