Created
November 16, 2015 22:52
-
-
Save LuxoftAKutsan/4e6ad7ef7afddfcc2fc6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <vector> | |
#include <algorithm> | |
typedef std::vector<std::string> EString; | |
template<class T> | |
struct Enum { | |
template<typename EType> | |
static std::string toString(EType etype) { | |
if ((etype < 0) || (etype > T::eString().size())) { | |
return "INVALID_ENUM"; | |
} | |
return T::eString()[static_cast<int>(etype)]; | |
} | |
static typename T::eType toEnum(std::string str) { | |
int res = - 1; | |
EString strings = T::eString(); | |
EString::iterator it = std::find(strings.begin(), strings.end(), str); | |
if (it != strings.end()) | |
res = std::distance(strings.begin(), it); | |
return static_cast<typename T::eType>(res); | |
} | |
}; | |
struct EStringInitializer { | |
EStringInitializer(const std::string& first){ | |
strings.push_back(first); | |
} | |
EStringInitializer& operator () (const std::string& value) { | |
strings.push_back(value); | |
return *this; | |
} | |
operator EString() { | |
return strings; | |
} | |
EString strings; | |
}; | |
struct MyEnum { | |
enum eType {ZERO, ONE, TWO}; | |
static EString eString () { | |
return EStringInitializer("ZERO")("ONE")("TWO"); | |
} | |
}; | |
int main() { | |
MyEnum::eType zero = MyEnum::ZERO; | |
std::cout << zero << " -> " << Enum<MyEnum>::toString(zero) << std::endl; | |
std::string one_str = "ONE"; | |
MyEnum::eType one = Enum<MyEnum>::toEnum("ONE"); | |
std::cout << one_str << " -> " << one << " -> " << Enum<MyEnum>::toString(one) << std::endl; | |
MyEnum::eType invalid1 = static_cast<MyEnum::eType>(-1); | |
std::cout << invalid1 << " -> " << Enum<MyEnum>::toString(invalid1) << std::endl; | |
MyEnum::eType invalid2 = static_cast<MyEnum::eType>(555); | |
std::cout << invalid2 << " -> " << Enum<MyEnum>::toString(invalid2) << std::endl; | |
std::string invalid_str = "Some invalid value"; | |
MyEnum::eType invalid3 = Enum<MyEnum>::toEnum(invalid_str); | |
std::cout << invalid_str << " -> " << invalid3 << " -> " << Enum<MyEnum>::toString(invalid3) << std::endl; | |
return 0; | |
} |
Author
LuxoftAKutsan
commented
Nov 16, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment