1 /* This file is part of libDAI - http://www.libdai.org/
3 * libDAI is licensed under the terms of the GNU General Public License version
4 * 2, or (at your option) any later version. libDAI is distributed without any
5 * warranty. See the file COPYING for more details.
7 * Copyright (C) 2006-2009 Joris Mooij [joris dot mooij at libdai dot org]
8 * Copyright (C) 2006-2007 Radboud University Nijmegen, The Netherlands
13 /// \brief Defines the DAI_ENUM macro
16 #ifndef __defined_libdai_enum_h
17 #define __defined_libdai_enum_h
22 #include <dai/exceptions.h>
25 /// Extends the C++ enum type by supporting input/output streaming and conversion to and from const char* and size_t
26 /** For more details see the source code.
30 * DAI_ENUM(colors,RED,GREEN,BLUE)
32 * defines a class \a colors encapsulating an
34 * enum {RED, GREEN, BLUE};
36 * which offers additional functionality over the plain \c enum keyword.
38 #define DAI_ENUM(x,val0,...) class x {\
40 enum value {val0,__VA_ARGS__};\
47 static char const* labelstring = #val0 "," #__VA_ARGS__;\
48 size_t pos_begin = 0;\
50 for( size_t pos_end = 0; ; pos_end++ ) {\
51 if( (labelstring[pos_end] == ',') || (labelstring[pos_end] == '\0') ) {\
52 if( (strlen( w ) == pos_end - pos_begin) && (strncmp( labelstring + pos_begin, w, pos_end - pos_begin ) == 0) ) {\
57 pos_begin = pos_end + 1;\
60 if( labelstring[pos_end] == '\0' )\
63 DAI_THROWE(UNKNOWN_ENUM_VALUE,"'" + std::string(w) + "' is not in [" + std::string(labelstring) + "]");\
66 operator value() const { return v; }\
68 operator size_t() const { return (size_t)v; }\
70 operator char const*() const {\
71 static char labelstring[] = #val0 "," #__VA_ARGS__;\
72 size_t pos_begin = 0;\
74 for( size_t pos_end = 0; ; pos_end++ )\
75 if( (labelstring[pos_end] == ',') || (labelstring[pos_end] == '\0') ) {\
76 if( (size_t)v == i ) {\
77 labelstring[pos_end] = '\0';\
78 return labelstring + pos_begin;\
81 pos_begin = pos_end + 1;\
86 friend std::istream& operator >> (std::istream& is, x& y) {\
93 friend std::ostream& operator << (std::ostream& os, const x& y) {\
94 os << (const char *)y;\