test_enum.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. tests/test_enums.cpp -- enumerations
  3. Copyright (c) 2016 Wenzel Jakob <[email protected]>
  4. All rights reserved. Use of this source code is governed by a
  5. BSD-style license that can be found in the LICENSE file.
  6. */
  7. #include "pybind11_tests.h"
  8. TEST_SUBMODULE(enums, m) {
  9. // test_unscoped_enum
  10. enum UnscopedEnum {
  11. EOne = 1,
  12. ETwo
  13. };
  14. py::enum_<UnscopedEnum>(m, "UnscopedEnum", py::arithmetic())
  15. .value("EOne", EOne)
  16. .value("ETwo", ETwo)
  17. .export_values();
  18. // test_scoped_enum
  19. enum class ScopedEnum {
  20. Two = 2,
  21. Three
  22. };
  23. py::enum_<ScopedEnum>(m, "ScopedEnum", py::arithmetic())
  24. .value("Two", ScopedEnum::Two)
  25. .value("Three", ScopedEnum::Three);
  26. m.def("test_scoped_enum", [](ScopedEnum z) {
  27. return "ScopedEnum::" + std::string(z == ScopedEnum::Two ? "Two" : "Three");
  28. });
  29. // test_binary_operators
  30. enum Flags {
  31. Read = 4,
  32. Write = 2,
  33. Execute = 1
  34. };
  35. py::enum_<Flags>(m, "Flags", py::arithmetic())
  36. .value("Read", Flags::Read)
  37. .value("Write", Flags::Write)
  38. .value("Execute", Flags::Execute)
  39. .export_values();
  40. // test_implicit_conversion
  41. class ClassWithUnscopedEnum {
  42. public:
  43. enum EMode {
  44. EFirstMode = 1,
  45. ESecondMode
  46. };
  47. static EMode test_function(EMode mode) {
  48. return mode;
  49. }
  50. };
  51. py::class_<ClassWithUnscopedEnum> exenum_class(m, "ClassWithUnscopedEnum");
  52. exenum_class.def_static("test_function", &ClassWithUnscopedEnum::test_function);
  53. py::enum_<ClassWithUnscopedEnum::EMode>(exenum_class, "EMode")
  54. .value("EFirstMode", ClassWithUnscopedEnum::EFirstMode)
  55. .value("ESecondMode", ClassWithUnscopedEnum::ESecondMode)
  56. .export_values();
  57. // test_enum_to_int
  58. m.def("test_enum_to_int", [](int) { });
  59. m.def("test_enum_to_uint", [](uint32_t) { });
  60. m.def("test_enum_to_long_long", [](long long) { });
  61. }