libDAI
enum.h
Go to the documentation of this file.
1 /* This file is part of libDAI - http://www.libdai.org/
2  *
3  * Copyright (c) 2006-2011, The libDAI authors. All rights reserved.
4  *
5  * Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
6  */
7 
8 
11 
12 
13 #ifndef __defined_libdai_enum_h
14 #define __defined_libdai_enum_h
15 
16 
17 #include <cstring>
18 #include <iostream>
19 #include <dai/exceptions.h>
20 
21 
23 
35 #define DAI_ENUM(x,val0,...) class x {\
36  public:\
37  enum value {val0,__VA_ARGS__};\
38 \
39  x() : v(val0) {}\
40 \
41  x(value w) : v(w) {}\
42 \
43  x(char const *w) {\
44  static char const* labelstring = #val0 "," #__VA_ARGS__;\
45  size_t pos_begin = 0;\
46  size_t i = 0;\
47  for( size_t pos_end = 0; ; pos_end++ ) {\
48  if( (labelstring[pos_end] == ',') || (labelstring[pos_end] == '\0') ) {\
49  if( (strlen( w ) == pos_end - pos_begin) && (strncmp( labelstring + pos_begin, w, pos_end - pos_begin ) == 0) ) {\
50  v = (value)i;\
51  return;\
52  } else {\
53  i++;\
54  pos_begin = pos_end + 1;\
55  }\
56  }\
57  if( labelstring[pos_end] == '\0' )\
58  break;\
59  }\
60  DAI_THROWE(UNKNOWN_ENUM_VALUE,"'" + std::string(w) + "' is not in [" + std::string(labelstring) + "]");\
61  }\
62 \
63  operator value() const { return v; }\
64 \
65  operator size_t() const { return (size_t)v; }\
66 \
67  operator char const*() const {\
68  static char labelstring[] = #val0 "," #__VA_ARGS__;\
69  size_t pos_begin = 0;\
70  size_t i = 0;\
71  for( size_t pos_end = 0; ; pos_end++ )\
72  if( (labelstring[pos_end] == ',') || (labelstring[pos_end] == '\0') ) {\
73  if( (size_t)v == i ) {\
74  labelstring[pos_end] = '\0';\
75  return labelstring + pos_begin;\
76  } else {\
77  i++;\
78  pos_begin = pos_end + 1;\
79  }\
80  }\
81  }\
82 \
83  friend std::istream& operator >> (std::istream& is, x& y) {\
84  std::string s;\
85  is >> s;\
86  y = x(s.c_str());\
87  return is;\
88  }\
89 \
90  friend std::ostream& operator << (std::ostream& os, const x& y) {\
91  os << (const char *)y;\
92  return os;\
93  }\
94 \
95  protected:\
96  value v;\
97 };
98 
99 
100 #endif