Convert enum value to std::string in C++ (C++ enum 转 string)
#pragma once #include <iostream> #include <vector> #define DEFINE_ENUM(name, ...)\ class name {\ public:\ typedef enum { __VA_ARGS__ } enum_type; \ \ name(enum_type v): v_(v) {}\ \ enum_type Value() const {\ return v_;\ }\ \ std::string ToString() const {\ static std::vector<std::string> m = GetMappings();\ auto i = static_cast<size_t>(v_);\ if (i > m.size()) {\ return #name ":-Invalid";\ }\ return m[i];\ }\ \ bool operator == (enum_type v) const {\ return v_ == v;\ }\ bool operator != (enum_type v) const {\ return v_ != v;\ }\ \ static std::string Name() {\ return #name;\ }\ \ friend std::ostream& operator << (std::ostream& stream, const name& v) {\ return stream << v.Value();\ }\ \ private:\ static std::vector<std::string> GetMappings() {\ std::vector<std::string> tokens;\ std::string s = #__VA_ARGS__; \ std::string token;\ for (char c : s) {\ if (c == ' ' || c == ',') {\ if (!token.empty()) {\ tokens.push_back(Name() + "::" + token);\ token.clear();\ }\ } else {\ token += c;\ }\ }\ return tokens;\ }\ \ private:\ enum_type v_;\ } DEFINE_ENUM(Weekday, Monday, Tuesday, // Monday Wednesday, // Thirsday, ); template<Weekday::enum_type day> class Test { public: static Weekday GetDay() { return day; }; }; int main() { Weekday day = Weekday::Monday; std::cout << day.ToString() << std::endl; std::cout << (day == Weekday::Thirsday) << std::endl; day = Weekday::Tuesday; std::cout << day.ToString() << std::endl; std::cout << Test<Weekday::Thirsday>::GetDay() << std::endl; return 0; }
Output:
Weekday::Monday 0 Weekday::Tuesday 3