00001
#ifndef DV_UTIL_ENUM2STR_H
00002
#define DV_UTIL_ENUM2STR_H
00003
00004
#include <stdexcept>
00005
#include <dvutil/tostring.h>
00006
00007
namespace Dv {
00008
namespace Util {
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
template<
typename E>
00028 class enum_parser {
00029
public:
00030
00031 typedef struct { E e;
const char* s; }
enum_entry;
00032
00033
00034
00035 static enum_entry enum_table[];
00036
00037 static const char*
E_NAME;
00038
00039
00040
00041
00042
00043 static const char*
enum2str(E e)
throw (std::logic_error) {
00044
static const std::string NAME(
"enum2str");
00045
for (
unsigned int i=0;
enum_table[i].
s; ++i)
00046
if (
enum_table[i].
e == e)
00047
return enum_table[i].
s;
00048
throw std::logic_error(NAME +
": cannot convert " +
00049
E_NAME +
" value " +
tostring(static_cast<int>(e)));
00050 }
00051
00052
00053
00054
00055
00056 static E
str2enum(
const std::string& s)
throw (std::logic_error) {
00057
static const std::string NAME(
"str2enum");
00058
for (
unsigned int i=0;
enum_table[i].
s ; ++i)
00059
if (
enum_table[i].
s == s)
00060
return enum_table[i].
e;
00061
throw std::logic_error(NAME +
": cannot convert '" + s +
"' to " +
E_NAME);
00062 }
00063 };
00064
00065
00066
00067
00068
00069
00070
template<
typename E>
00071
const char*
00072 enum2str(E e) {
00073
return enum_parser<E>::enum2str(e);
00074 }
00075
00076
00077
00078
00079
00080
00081
template<
typename E>
00082 E
00083 str2enum(
const std::string& s) {
00084
return enum_parser<E>::str2enum(s);
00085 }
00086
00087 }}
00088
#endif