Skip to content

Commit

Permalink
nb::handle: make bool conversion explicit to avoid ambiguity with int…
Browse files Browse the repository at this point in the history
…eger conversions in derived types (#173)

An `explicit operator bool()` can still be used in conditional tests without a cast (`if (h) { ... }`) and is a better match for the explicitness of, for example, `operator int()` in `nb::int_`. Without this change, if you write
```
void fn(nb::int_ ival) {
    int i = ival;
    printf("%d\n", i);
}
```
then `fn(nb::int_(42))` will print 1. (Only implicit conversions are allowed by the initialization style used, so the implicit `operator bool` in `nb::handle` is eligible while the explicit `operator int` in `nb::int_` is not.)
  • Loading branch information
oremanj committed Apr 5, 2023
1 parent 9ccb980 commit c4be1b6
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion include/nanobind/nb_types.h
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ class handle : public detail::api<handle> {
return *this;
}

NB_INLINE operator bool() const { return m_ptr != nullptr; }
NB_INLINE explicit operator bool() const { return m_ptr != nullptr; }
NB_INLINE PyObject *ptr() const { return m_ptr; }
NB_INLINE static bool check_(handle) { return true; }

Expand Down

0 comments on commit c4be1b6

Please sign in to comment.