Scarab  v2.9.1
Project 8 C++ Utility Library
test_enum.cpp
Go to the documentation of this file.
1 /*
2  tests/test_enums.cpp -- enumerations
3 
4  Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5 
6  All rights reserved. Use of this source code is governed by a
7  BSD-style license that can be found in the LICENSE file.
8 */
9 
10 #include "pybind11_tests.h"
11 
13  // test_unscoped_enum
14  enum UnscopedEnum {
15  EOne = 1,
16  ETwo
17  };
18  py::enum_<UnscopedEnum>(m, "UnscopedEnum", py::arithmetic(), "An unscoped enumeration")
19  .value("EOne", EOne, "Docstring for EOne")
20  .value("ETwo", ETwo, "Docstring for ETwo")
21  .export_values();
22 
23  // test_scoped_enum
24  enum class ScopedEnum {
25  Two = 2,
26  Three
27  };
28  py::enum_<ScopedEnum>(m, "ScopedEnum", py::arithmetic())
29  .value("Two", ScopedEnum::Two)
30  .value("Three", ScopedEnum::Three);
31 
32  m.def("test_scoped_enum", [](ScopedEnum z) {
33  return "ScopedEnum::" + std::string(z == ScopedEnum::Two ? "Two" : "Three");
34  });
35 
36  // test_binary_operators
37  enum Flags {
38  Read = 4,
39  Write = 2,
40  Execute = 1
41  };
42  py::enum_<Flags>(m, "Flags", py::arithmetic())
43  .value("Read", Flags::Read)
44  .value("Write", Flags::Write)
45  .value("Execute", Flags::Execute)
46  .export_values();
47 
48  // test_implicit_conversion
49  class ClassWithUnscopedEnum {
50  public:
51  enum EMode {
52  EFirstMode = 1,
53  ESecondMode
54  };
55 
56  static EMode test_function(EMode mode) {
57  return mode;
58  }
59  };
60  py::class_<ClassWithUnscopedEnum> exenum_class(m, "ClassWithUnscopedEnum");
61  exenum_class.def_static("test_function", &ClassWithUnscopedEnum::test_function);
62  py::enum_<ClassWithUnscopedEnum::EMode>(exenum_class, "EMode")
63  .value("EFirstMode", ClassWithUnscopedEnum::EFirstMode)
64  .value("ESecondMode", ClassWithUnscopedEnum::ESecondMode)
65  .export_values();
66 
67  // test_enum_to_int
68  m.def("test_enum_to_int", [](int) { });
69  m.def("test_enum_to_uint", [](uint32_t) { });
70  m.def("test_enum_to_long_long", [](long long) { });
71 
72  // test_duplicate_enum_name
73  enum SimpleEnum
74  {
75  ONE, TWO, THREE
76  };
77 
78  m.def("register_bad_enum", [m]() {
79  py::enum_<SimpleEnum>(m, "SimpleEnum")
80  .value("ONE", SimpleEnum::ONE) //NOTE: all value function calls are called with the same first parameter value
81  .value("ONE", SimpleEnum::TWO)
82  .value("ONE", SimpleEnum::THREE)
83  .export_values();
84  });
85 }
Binds C++ enumerations and enumeration classes to Python.
Definition: pybind11.h:1537
Annotation to mark enums as an arithmetic type.
Definition: attr.h:71
test_initializer enums("enums", test_submodule_enums)
class_ & def_static(const char *name_, Func &&f, const Extra &... extra)
Definition: pybind11.h:1118
#define TEST_SUBMODULE(name, variable)
bool typename Extra class_ & def(const char *name_, Func &&f, const Extra &... extra)
Definition: pybind11.h:1110