verlsk
verlsk

Reputation: 21

Can I use a generic enum type as a parameter of a function?

I want to pass a parameter to a function, which is a enum. But I have many different enums created so I want that function to be useful for all of them. Is it possible? What I want to do is something like this:

enum Enum a {one, two};
enum Enum b {red, white};

void useEnum (enum anyEnum){
    //do something
}

Upvotes: 1

Views: 830

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122707

You can make the function accept any type you like by making it a template:

enum Enum a {one, two};
enum Enum b {red, white};

template <typename EnumType>
void useEnum (EnumType anyEnum){
    //do something
}

However, I strongly doubt that it is a good idea to write one function that deals with numbers and colors. Without knowing any more context I would rather go for overloads or even more explicit:

void useNumber(a number){}
void useColor(b color){}

PS: If you stay with one function for different enums, then be aware that you basically go a step backwards. The main purpose of enums is to have type safe enumerations (enum class adds more typesafety), while inside your useEnum the only thing that the two enums have in common is that they have elements with underlying values 0 and 1 and thats what you will be working on. At that point using the enums has no more advantage compared to using raw 0 and 1.

Upvotes: 3

Related Questions