1

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
}
5
  • anything is possible, but as always it depends on the details. What is //do something ? Commented Oct 7, 2019 at 15:52
  • Make a generic function, what's the problem here? Commented Oct 7, 2019 at 15:53
  • 7
    Have you heard about our lord and savoir: Templates? Commented Oct 7, 2019 at 15:54
  • In your example, the values for one and red may be identical -- how than shall your function deal with that? Commented Oct 7, 2019 at 15:55
  • ... Or you could use int or any other integer type, which can hold all the values of all the enums (best would be std::common_type<std::underlying_type<a>, std::underlying_type<b>>, but int is sufficient in most cases) Commented Oct 7, 2019 at 16:03

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, that was what I was looking for. The names were just examples.
@verlsk dont miss the just added PS, and if you like you may accept the answer of course ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.