Skip to content

Commit

Permalink
type_caster<std::optional>: support non-assignable types (#358)
Browse files Browse the repository at this point in the history
  • Loading branch information
WKarel committed Nov 9, 2023
1 parent 61ca0f9 commit 0c9b648
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
2 changes: 1 addition & 1 deletion include/nanobind/stl/optional.h
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ struct type_caster<std::optional<T>> {
"type caster was registered to intercept this particular "
"type, which is not allowed.");

value = caster.operator cast_t<T>();
value.emplace(caster.operator cast_t<T>());

return true;
}
Expand Down
11 changes: 11 additions & 0 deletions tests/test_stl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ struct Copyable {
~Copyable() { destructed++; }
};

struct NonAssignable {
int value = 5;

NonAssignable &operator=(const NonAssignable &) = delete;
};

struct StructWithReadonlyMap {
std::map<std::string, uint64_t> map;
};
Expand Down Expand Up @@ -102,6 +108,10 @@ NB_MODULE(test_stl_ext, m) {
.def(nb::init<int>())
.def_rw("value", &Copyable::value);

nb::class_<NonAssignable>(m, "NonAssignable")
.def(nb::init<>())
.def_rw("value", &NonAssignable::value);

nb::class_<StructWithReadonlyMap>(m, "StructWithReadonlyMap")
.def(nb::init<>())
.def_ro("map", &StructWithReadonlyMap::map);
Expand Down Expand Up @@ -254,6 +264,7 @@ NB_MODULE(test_stl_ext, m) {
m.def("optional_ret_opt_none", []() { return std::optional<Movable>(); });
m.def("optional_unbound_type", [](std::optional<int> &x) { return x; }, nb::arg("x") = nb::none());
m.def("optional_unbound_type_with_nullopt_as_default", [](std::optional<int> &x) { return x; }, nb::arg("x") = std::nullopt);
m.def("optional_non_assignable", [](std::optional<NonAssignable> &x) { return x; });

// ----- test43-test50 ------
m.def("variant_copyable", [](std::variant<Copyable, int> &) {});
Expand Down
4 changes: 4 additions & 0 deletions tests/test_stl.py
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,10 @@ def test42_std_optional_unbound_type():
)


def test42a_std_optional_non_assignable():
assert t.optional_non_assignable(t.NonAssignable()).value == 5


def test43_std_variant_copyable(clean):
t.variant_copyable(t.Copyable())
t.variant_copyable(5)
Expand Down

0 comments on commit 0c9b648

Please sign in to comment.