ConsecutiveEnumFactory.h
Go to the documentation of this file.
1 #ifndef _utl_ConsecutiveEnumFactory_h_
2 #define _utl_ConsecutiveEnumFactory_h_
3 
4 #include <utl/AugerException.h>
5 #include <utl/ThrowPolicy.h>
6 
7 #include <sstream>
8 
9 
10 namespace utl {
11 
111  template<
112  typename EnumType,
113  EnumType last,
114  const char* const tags[],
115  class NoConversionPolicy = ThrowPolicy<EnumType, utl::IOFailureException>,
116  EnumType first = static_cast<EnumType>(0)
117  >
120  template<typename T>
121  static
122  EnumType
123  Handle(const T& t)
124  {
125  std::ostringstream os;
126  os << "Cannot convert " << t << " to any of the valid enumerators:";
127  for (unsigned int i = 0; i < kNumEnum; ++i)
128  os << ' ' << tags[i];
129  os << " (with values from " << first << " to " << last << ").";
130  return NoConversionPolicy::Handle(os.str());
131  }
132  public:
135  const static unsigned int kNumEnum = last - first + 1;
137  static
138  EnumType
139  Create(const int k)
140  {
141  if (first <= k && k <= last)
142  return static_cast<EnumType>(k);
143  return Handle(k);
144  }
146  static
147  EnumType
148  Create(const std::string& tag)
149  {
150  // This linear search may be replaced by a more sophisticated
151  // look-up strategy, but for this case it does not seem worth of
152  // it. In fact, given a (supposed) typical quantity of (at most)
153  // 10 enumerators, this simple loop could not be outperformed
154  // (even discarding some initialization procedures that may
155  // be needed).
156  // Even more, who would be able to quantify the difference given
157  // that number of values!
158  for (unsigned int i = 0; i < kNumEnum; ++i)
159  if (tags[i] == tag)
160  return static_cast<EnumType>(i);
161  return Handle(tag);
162  }
163  };
164 
165 }
166 
167 
168 #endif
Simple factory to create an enumerator for a given enumeration.
static EnumType Create(const int k)
int version of the overloaded creation method.
static EnumType Handle(const T &t)
Error handling.
static EnumType Create(const std::string &tag)
std::string version of the overloaded creation method.

, generated on Tue Sep 26 2023.