1

I was wondering if there is any way to pass an integer to a function which expects a enum type.

I need to use this function: void SetValue(enumtypevalue){ variable = value} that was made by a work mate and the enum is something like:

typedef enum
{
   Obj1 = 0,
   Obj2 = 1,
   ...
   Objn = m,
}enumtype;

The thing is that this function is on a library I use in my program and there I know the number of the enum but not the name (Obj1, Obj2...) so I was wondering if its possible to do something like SetValue(4) instead of SetValue(Obj1)so my mate doesn't have to overwritte/change it and I don't have to hardcode all the enum (which is not small).

I know it sounds so stupid to pretend pass one type instead of another but if you pass 'Obj1' to the function its like saying '0' because they are related so that's why I make this 'fool' question.

Thanks.

4
  • 5
    Are you by any chance meaning enum instead of structure? Commented Jun 19, 2015 at 14:25
  • yes sorry, what a fail. I already edited it thanks Commented Jun 19, 2015 at 14:35
  • Don't do typedef enum {...} enumName. That is not what typedef is for. Commented Jun 19, 2015 at 15:16
  • The idea was to not have to change my mate's work but thank you. I still don't know why someone voted down my question but nvm. Commented Jun 19, 2015 at 15:26

1 Answer 1

6

You can cast an integer to an enum type with static_cast, e.g.

SetValue(static_cast<enumtype>(4));

That is an unmaintainable last resort, though. Part of the point of enums is to have something more meaningful than bare integer constants. Another reason why it's a good thing to use them is because integer constants may need to be changed for some reason, and it's then very hard to go and find all the places the constants are used in code that calls the function and change them accordingly.

Can't you get access to the enum type by #include-ing a header file from somewhere?

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

1 Comment

Hi, thanks! I didn't know you use the statc cast there too (I never think about static_cast dunno why O.o) Btw... I'm not really going to write the number as you mention. Its something more complicated so if the number changes this will not be affected :) Thank you for your answer!

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.