Skip to content

Use cpp17 constexpr for casting #3113

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 17 additions & 7 deletions include/pybind11/cast.h
Original file line number Diff line number Diff line change
Expand Up @@ -887,13 +887,23 @@ T cast(const handle &handle) { return T(reinterpret_borrow<object>(handle)); }
template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
object cast(T &&value, return_value_policy policy = return_value_policy::automatic_reference,
handle parent = handle()) {
using no_ref_T = typename std::remove_reference<T>::type;
if (policy == return_value_policy::automatic)
policy = std::is_pointer<no_ref_T>::value ? return_value_policy::take_ownership :
std::is_lvalue_reference<T>::value ? return_value_policy::copy : return_value_policy::move;
else if (policy == return_value_policy::automatic_reference)
policy = std::is_pointer<no_ref_T>::value ? return_value_policy::reference :
std::is_lvalue_reference<T>::value ? return_value_policy::copy : return_value_policy::move;
if (policy == return_value_policy::automatic) {
if PYBIND11_CPP17_CONSTEXPR (std::is_pointer<std::remove_reference<T>>::value) {
policy = return_value_policy::take_ownership;
} else if PYBIND11_CPP17_CONSTEXPR (std::is_lvalue_reference<T>::value) {
policy = return_value_policy::copy;
} else {
policy = return_value_policy::move;
}
} else if (policy == return_value_policy::automatic_reference) {
if PYBIND11_CPP17_CONSTEXPR (std::is_pointer<std::remove_reference<T>>::value) {
policy = return_value_policy::reference;
} else if PYBIND11_CPP17_CONSTEXPR (std::is_lvalue_reference<T>::value) {
policy = return_value_policy::copy;
} else {
policy = return_value_policy::move;
}
}
return reinterpret_steal<object>(detail::make_caster<T>::cast(std::forward<T>(value), policy, parent));
}

Expand Down
6 changes: 6 additions & 0 deletions include/pybind11/detail/common.h
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,12 @@
# define PYBIND11_MAYBE_UNUSED __attribute__ ((__unused__))
#endif

#if defined(PYBIND11_CPP17)
# define PYBIND11_CPP17_CONSTEXPR constexpr
#else
# define PYBIND11_CPP17_CONSTEXPR
#endif

/* Don't let Python.h #define (v)snprintf as macro because they are implemented
properly in Visual Studio since 2015. */
#if defined(_MSC_VER) && _MSC_VER >= 1900
Expand Down