The*_* do 1 c++ enums iostream
我想能够写:
cout << enumalpha << Monday;
Run Code Online (Sandbox Code Playgroud)
并在控制台上打印:
星期一
PS Monday是一个枚举类型.
好吧,让我们去所有预处理器然后:)
预期使用方式:
DEFINE_ENUM(DayOfWeek, (Monday)(Tuesday)(Wednesday)
(Thursday)(Friday)(Saturday)(Sunday))
int main(int argc, char* argv[])
{
DayOfWeek_t i = DayOfWeek::Monday;
std::cout << i << std::endl; // prints Monday
std::cin >> i >> std::endl; // reads the content of a string and
// deduce the corresponding enum value
}
Run Code Online (Sandbox Code Playgroud)
黑魔法,涉及有用的Boost.Preprocessor库.
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <boost/preprocessor/seq/enum.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#define DEFINE_ENUM_VAL_TO_STR(r, data, elem) \
case BOOST_PP_CAT(data, BOOST_PP_CAT(::, elem)): \
return out << BOOST_PP_STRINGIZE(elem);
#define DEFINE_ENUM_STR_TO_VAL(r, data, elem) \
if (s == BOOST_PP_STRINGIZE(elem)) \
{ i = BOOST_PP_CAT(data, BOOST_PP_CAT(::, elem)) ; } else
#define DEFINE_ENUM(Name, Values) \
struct Name { \
enum type { \
Invalid = 0, \
BOOST_PP_SEQ_ENUM(Values) \
}; \
}; \
typedef Name::type Name##_t; \
std::ostream& operator<<(std::ostream& out, Name##_t i) { \
switch(i) { \
BOOST_PP_SEQ_FOR_EACH(DEFINE_ENUM_VAL_TO_STR, Name, Values) \
default: return out << "~"; } } \
std::istream& operator>>(std::istream& in, Name##_t& i) { \
std::string s; in >> s; \
BOOST_PP_SEQ_FOR_EACH(DEFINE_ENUM_STR_TO_VAL, Name, Values) \
{ i = Name##::Invalid; } }
Run Code Online (Sandbox Code Playgroud)
有更好的方法,我个人使用这个小宏来存储所有在一对排序很好的对矢量,静态的类型,它还允许我迭代枚举的值,如果情绪(或需要)罢工:)
虽然没有语言支持,但这是非常不幸的.我更喜欢,如果有,枚举对于代码集非常方便...