native_enum.h 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
  2. // Copyright (c) 2022-2025 The pybind Community.
  3. // All rights reserved. Use of this source code is governed by a
  4. // BSD-style license that can be found in the LICENSE file.
  5. #pragma once
  6. #include "detail/common.h"
  7. #include "detail/native_enum_data.h"
  8. #include "detail/type_caster_base.h"
  9. #include "cast.h"
  10. #include <cassert>
  11. #include <limits>
  12. #include <type_traits>
  13. #include <typeindex>
  14. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
  15. /// Conversions between Python's native (stdlib) enum types and C++ enums.
  16. template <typename EnumType>
  17. class native_enum : public detail::native_enum_data {
  18. public:
  19. using Underlying = typename std::underlying_type<EnumType>::type;
  20. native_enum(const object &parent_scope,
  21. const char *name,
  22. const char *native_type_name,
  23. const char *class_doc = "")
  24. : detail::native_enum_data(
  25. parent_scope, name, native_type_name, class_doc, std::type_index(typeid(EnumType))) {
  26. if (detail::get_local_type_info(typeid(EnumType)) != nullptr
  27. || detail::get_global_type_info(typeid(EnumType)) != nullptr) {
  28. pybind11_fail(
  29. "pybind11::native_enum<...>(\"" + enum_name_encoded
  30. + "\") is already registered as a `pybind11::enum_` or `pybind11::class_`!");
  31. }
  32. if (detail::global_internals_native_enum_type_map_contains(enum_type_index)) {
  33. pybind11_fail("pybind11::native_enum<...>(\"" + enum_name_encoded
  34. + "\") is already registered!");
  35. }
  36. arm_finalize_check();
  37. }
  38. /// Export enumeration entries into the parent scope
  39. native_enum &export_values() {
  40. assert(!export_values_flag); // Catch redundant calls.
  41. export_values_flag = true;
  42. return *this;
  43. }
  44. /// Add an enumeration entry
  45. native_enum &value(char const *name, EnumType value, const char *doc = nullptr) {
  46. // Disarm for the case that the native_enum_data dtor runs during exception unwinding.
  47. disarm_finalize_check("value after finalize");
  48. members.append(make_tuple(name, static_cast<Underlying>(value)));
  49. if (doc) {
  50. member_docs.append(make_tuple(name, doc));
  51. }
  52. arm_finalize_check(); // There was no exception.
  53. return *this;
  54. }
  55. native_enum(const native_enum &) = delete;
  56. native_enum &operator=(const native_enum &) = delete;
  57. };
  58. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
  59. #else
  60. #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
  61. #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)