c++ - Modifying scoped enum by reference -


i increasingly finding scoped enums unwieldy use. trying write set of function overloads including template scoped enums sets/initializes value reference--something this:

void set_value(int& val); void set_value(double& val); template <typename enum> set_value(enum& val); 

however, don't quite see how write templated version of set_value without introducing multiple temporary values:

template <typename enum> set_value(enum& val) {   std::underlying_type_t<enum> raw_val;   set_value(raw_val);    // calls appropriate "primitive" overload   val = static_cast<enum>(raw_val); } 

i believe static_cast introduces second temporary value in addition raw_val. suppose it's possible 1 or both of these optimized away compiler, , in case shouldn't make difference in terms of performance since set_value call generate temporary values (assuming it's not inlined), still seems inelegant. like this:

template <typename enum> set_value(enum& val) {   set_value(static_cast<std::underlying_type_t<enum>&>(val)); } 

... isn't valid (nor corresponding code using pointers directly instead of references) because scoped enums aren't related underlying primitives via inheritance.

i use reinterpret_cast, which, preliminary testing, appears work (and can't think of reason why wouldn't work), seems frowned upon in c++.

is there "standard" way this?

i use reinterpret_cast, which, preliminary testing, appears work (and can't think of reason why wouldn't work), seems frowned upon in c++.

indeed, reinterpret_cast undefined behavior violation of strict aliasing rule.

eliminating single mov instruction (or otherwise, more or less, copying register's worth of data) premature micro-optimization. compiler able take care of it.

if performance important, follow optimization process: profile, disassemble, understand compiler's interpretation, , work within defined rules.

at glance, (and compiler) might have easier time functions t get_value() instead of void set_value(t). flow of data , initialization make more sense, although type deduction lost. can regain deduction through tag types, if that's important.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -