How can I extend a lexical cast to support enumerated types?

Viewed 11974

I have the following function that will convert a string into a numeric data type:

template <typename T>
bool ConvertString(const std::string& theString, T& theResult)
{
    std::istringstream iss(theString);
    return !(iss >> theResult).fail();
}

This does not work for enumerated types, however, so I have done something like this:

template <typename T>
bool ConvertStringToEnum(const std::string& theString, T& theResult)
{
    std::istringstream iss(theString);
    unsigned int temp;
    const bool isValid = !(iss >> temp).fail();
    theResult = static_cast<T>(temp);
    return isValid;
}

(I'm making the assumption that theString has a valid value for the enumerated type; I'm using this mainly for simple serialization)

Is there a way to create a single function that combines both of these?

I've played a bit with the template arguments but haven't come up with anything; it'd just be nice not to have to call one function for enumerated types and another for everything else.

Thank you

2 Answers

And just to "complete" the question, in C++0x we can just do this:

typedef typename std::underlying_type<T>::type safe_type;

In place of Johannes get_etype trick.

Related