better-enums icon indicating copy to clipboard operation
better-enums copied to clipboard

Static functions for enum types

Open reddigfabian opened this issue 4 years ago • 1 comments

I'm trying to emulate java's ability to add a static function to an enum class but using better enums.

`namespace playground { BETTER_ENUM(Vegetable, int, potato, brocolli, carrot )

std::string getColor(Vegetable toGet) {
    switch (toGet) {
        case Vegetable::potato:
            return "brown";
        case Vegetable::brocolli:
            return "green";
        case Vegetable::carrot:
            return "orange";
        default:
            return "unknown";
    }
}

}`

I'd like to be able to simply call Vegetable::getColor(Vegetable::carrot), for example. Is there any way to add functions to the class generated by better enums?

reddigfabian avatar May 03 '21 14:05 reddigfabian

You may be able to use the default constructors override macro to either:

  • Give enums a public constructor, and derive a class from them.
  • Inject arbitrary code into the definition of an enum, because that's what the macro does.

aantron avatar May 04 '21 16:05 aantron