dimanche 5 avril 2015

C++ convert string to enum?

I'm trying to convert a string to an enumerated type on Linux. I found this code on stackoverflow for doing this very thing, but am not sure I'm using function templates correctly. It compiles fine.



template <typename T>
typename boost::enable_if< boost::is_enum<T>, bool>::type
convert_string(const std::string& theString, T& theResult)
{
typedef typename std::underlying_type<T>::type safe_type;

std::istringstream iss(theString);
safe_type temp;
const bool isValid = !(iss >> temp).fail();
theResult = static_cast<T>(temp);

return isValid;
}


And here I'm trying to make proper use of it.



enum TestType {
A1,
B2,
C3
};

string s = "A1";
TestType tt;

convert_string(s, tt);


The problem is that convert_string fails and tt is always 0 after the call. Also, the enum is located within an IDL for a middleware, but I'm testing with this.


Aucun commentaire:

Enregistrer un commentaire