0

In Python, I can initialize an enum from a string using standard construction:

class A(Enum):
  A = 'a'
a = A('a')

This is helpful for reading configurations from external files.

However, once I move this enum to C++ and bind it with pybind, __init__() can only accept ints...

Is there an option to bind a custom initializer to the binded enum so that the string-initializer syntax A('a') will still work?

liorda
  • 1,552
  • 2
  • 15
  • 38
  • https://pybind11.readthedocs.io/en/stable/classes.html#enumerations-and-internal-types – TooTone Aug 08 '23 at 18:14
  • 2
    @TooTone can you be more specific? I couldn't find an answer in the docs – liorda Aug 08 '23 at 18:16
  • The problem is that in your Python example, the enumerated value is a string, which is why that constructor works. Had it been an integer, you wouldn't be able to do that. And C++ doesn't support enumerations with string values. – Dan Mašek Aug 08 '23 at 20:40
  • That said, if you want to have an enumeration of integers and add a way to construct their instances by passing in a string representing the name of the enumerated value (in this case it would have to be `A('A')``... that wouldn't be too difficult to do. There's already a dictionary mapping names to values (I mention it [here](https://stackoverflow.com/a/76682936/3962537)), so you could implement some factory function even in pure Python. – Dan Mašek Aug 08 '23 at 20:47

0 Answers0