When a function f
uses an enum
as argument, what's the simplest way to call f
with an int
instead?
(1) This:
enum State {low=5, high=10}; void f(State t) { } void g(int t) { f(t); } int main() { g(5); }
triggers the error
invalid conversion from 'int' to 'State' [-fpermissive]
.(2) Is it safe to do a simple cast in this case?
void g(int t) { f((State) t); }
or is there a better way?
(3) The only "correct" solution I found to have a function
g
with anint
parameter is:void g(int t) { switch (t) { case 5: f(low); break; case 10: f(high); break; } }
Which of these solutions are correct?
I've already read converting from int to enum and using enum says invalid conversion from 'int' to 'type', but I'm looking for a simpler solution without complexity like static_cast<periods>(atoi(min_prd.c_str()))
, and I want to compare the different possible solutions, thus it is not a duplicate.
Also, my question is not covered by What is the difference between static_cast<> and C style casting?.