How to make a listing?

I have a third-party unscoped enum (which I cannot change) that I really would like to pass into my own enumeration area. How can I provide something like a conversion operator?

What I would like to do is something like this:

#include <iostream> enum ThirdPartyLetter { A=4, B=5 }; enum class MyNumber { ONE=1, TWO=2 // This doesn't compile, of course /*Number(const ThirdPartyLetter& rhs) { if(rhs == ThirdPartyLetter::A) { return ONE; } else { return TWO; } }*/ }; int main() { ThirdPartyLetter letter = ThirdPartyLetter::A; MyNumber number = static_cast<MyNumber>(letter); // Without the cast, this prints 4 (an invalid enum value!) std::cout << int(number) << std::endl; } 

Is there a way to provide some kind of drop from ThirdPartyNumber to MyNumber ?

+5
source share
1 answer

The idiomatic way to do this at compile time in C ++ is using traits.
As an example:

 enum Foo { ONE, TWO }; enum Bar { THREE, FOUR }; template<Foo> struct conv; template<> struct conv<Foo::ONE> { static constexpr Bar value = Bar::THREE; }; template<> struct conv<Foo::TWO> { static constexpr Bar value = Bar::FOUR; }; 

If you want to do this at run time, the switch might be a good fit.
Anyway, you can still use traits to centralize the transformation logic and do something like this:

 Bar get(Foo choice) { switch(choice) { case Foo::ONE: return conv<ONE>::value; case Foo::TWO: return conv<TWO>::value; } } 
+8
source

Source: https://habr.com/ru/post/1262481/


All Articles