Skip to content

Instantly share code, notes, and snippets.

@LuxoftAKutsan
Created November 16, 2015 22:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LuxoftAKutsan/4e6ad7ef7afddfcc2fc6 to your computer and use it in GitHub Desktop.
Save LuxoftAKutsan/4e6ad7ef7afddfcc2fc6 to your computer and use it in GitHub Desktop.
#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;
}
@LuxoftAKutsan
Copy link
Author

➜  /tmp  g++ ./enum.cpp -std=c++98 -pedantic && ./a.out  
0 -> ZERO
ONE -> 1 -> ONE
-1 -> INVALID_ENUM
555 -> INVALID_ENUM
Some invalid value -> -1 -> INVALID_ENUM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment