I have inherited a template to convert a string to a numerical value, and want to apply it to convert to boolean. I am not very experienced with the stringstream and locale classes. I do seem to be getting some odd behaviour, and I am wondering if someone could please explain it to me?
template<typename T> T convertFromString( const string& str ) const {
std::stringstream SStream( str );
T num = 0;
SStream >> num;
return num;
}
This works fine until I try the boolean conversion
string str1("1");
int val1 = convertFromString<int>(str1); // ok
string str2("true");
bool val2 = convertFromString<bool>(str2); // val2 is _false_
I spent some time tracking down the problem. I have confirmed that the locale's truename() returns "true".
The problem seems to be with the initialisation of the variable num. I can change the template to this and it works:
template<typename T> T convertFromString( const string& str ) const {
std::stringstream SStream( str );
T num; // <----------------------- Changed here
SStream >> num;
return num;
}
string str2("true");
bool val2 = convertFromString<bool>(str2); // val2 is _true_
Why does it work? I accept that initialising a bool with '0' is wrong, but why would this cause the SStream>>num
conversion to fail?