Detection of enum as template parameter

O

Old Wolf

I have code like this:

template<typename T>
T convert_string (std::string const &s)
{
std::istringstream iss(s);
T t;
iss >> t;
return t;
}

However, if T happens to be an enum then the code fails (gcc gives
a compile error, bcc compiles it by using a temporary integer for
the call to operator>>).

Is there some way I can amend this function to work with enums?
(It should treat them as an integer type).

The best I have come up with so far is to declare some sort
of global class:

template<typename T> struct known_enum<T> { static bool x = false; }

and then specialize it for all enums which might happen to be
a template parameter for convert_string:

template<> struct known_enum<MyEnum> { static bool x = true; }

and in convert_string, do a check:

if (known_enum<T>::x)
.........

Alternatively, I could explicitly specialize convert_string<>
for every enum it might come in contact with.
 
R

Rolf Magnus

shivank said:
Typecast it, it will work :)

iss >> (int)t;

Doesn't really sound like a useful solution, considering the OP wants it in
a template. Think of:

double x = convert_string<double>("1.234");
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,668
Latest member
SamiraShac

Latest Threads

Top