|
46 | 46 | #include "options.h"
|
47 | 47 | #include "detail/class.h"
|
48 | 48 | #include "detail/init.h"
|
| 49 | +#include "detail/typeid.h" |
49 | 50 |
|
50 | 51 | #include <memory>
|
51 | 52 | #include <vector>
|
@@ -1569,6 +1570,23 @@ inline str enum_name(handle arg) {
|
1569 | 1570 | return "???";
|
1570 | 1571 | }
|
1571 | 1572 |
|
| 1573 | +template <typename Type, typename Scalar, bool is_convertible = true> |
| 1574 | +struct enum_value { |
| 1575 | + static Scalar run(handle arg) { |
| 1576 | + Type value = pybind11::cast<Type>(arg); |
| 1577 | + return static_cast<Scalar>(value); |
| 1578 | + } |
| 1579 | +}; |
| 1580 | + |
| 1581 | +template <typename Type, typename Scalar> |
| 1582 | +struct enum_value<Type, Scalar, false> { |
| 1583 | + static Scalar run(handle) { |
| 1584 | + throw pybind11::cast_error( |
| 1585 | + "Enum for " + type_id<Type>() + " is not convertible to " + |
| 1586 | + type_id<Scalar>()); |
| 1587 | + } |
| 1588 | +}; |
| 1589 | + |
1572 | 1590 | struct enum_base {
|
1573 | 1591 | enum_base(handle base, handle parent) : m_base(base), m_parent(parent) { }
|
1574 | 1592 |
|
@@ -1728,8 +1746,14 @@ template <typename Type> class enum_ : public class_<Type> {
|
1728 | 1746 | : class_<Type>(scope, name, extra...), m_base(*this, scope) {
|
1729 | 1747 | constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value;
|
1730 | 1748 | constexpr bool is_convertible = std::is_convertible<Type, Scalar>::value;
|
| 1749 | + auto property = handle((PyObject *) &PyProperty_Type); |
1731 | 1750 | m_base.init(is_arithmetic, is_convertible);
|
1732 | 1751 |
|
| 1752 | + attr("value") = property( |
| 1753 | + cpp_function( |
| 1754 | + &detail::enum_value<Type, Scalar, is_convertible>::run, |
| 1755 | + pybind11::name("value"), is_method(*this))); |
| 1756 | + |
1733 | 1757 | def(init([](Scalar i) { return static_cast<Type>(i); }), arg("value"));
|
1734 | 1758 | def("__int__", [](Type value) { return (Scalar) value; });
|
1735 | 1759 | #if PY_MAJOR_VERSION < 3
|
|
0 commit comments