c++ - Pass an enum to a function taking a reference to int -
dereferencing type-punned
i have enum
enum agentstatus { kstopped = 0, krunning, kidle, knagentstatus };
i need pass function of external library many overloaded variants. want pass sec argument:
dimservice::dimservice(const char*, int&); dimservice::dimservice(const char*, char*); ...
if cast (int&) of enum variable, infamous warning :
warning: dereferencing type-punned pointer break strict-aliasing rules
if cast (int)
invalid conversion ‘int’ ‘char*’ error: initializing argument 2 of ‘dimservice::dimservice(const char*, char*)’
what right way ?
the reply bill right reply technically.
1) approach
another way if need rid of enum-ness of type create type int itself.
typedef int myenum; enum { const1 = 0, etc... };
and utilize normal. compiler not grab bad assignments of values, since can tag declarations myenum type should simple plenty follow happening, , can pass variables anywhere says int.
2) unsafe approach
never this!
enumtype v = enumvalue_... myfunction( *((int*)&v) );
or this...
#define make_int_ref(v) *((int*)&(v)) myfunction( make_int_ref(v) );
the reason because compiler can automatically take type utilize enum. might take int or might take char. can not sure across different compilers , platforms. if seek casting enum end unportable code , unsafe code, because writing such cast can overwrite other values.
c++ casting enums
No comments:
Post a Comment