I have some existing code that compiles fine with Visual Studio 2010 but gives an error with Visual Studio 2013. The code simply extracts a string from an istringstream and checks whether the conversion was successful or not:
bool okFlag = false;
istringstream s;
string myStr;
<snip>
okFlag = s >> myStr;
The error is:
error C2440: '=' : cannot convert from 'std::basic_istream<char,std::char_traits<char>>' to 'bool'
I guess that in C++11, the return type of the conversion is not bool. What is the correct way of doing it? Is it possible to have code that satisfies both VS2010 and VS2013?
In C++11 basic_ios::operator bool is explicit, while the C++03 user defined conversion to void * was implicitly convertible to bool. To fix your code you need to explicitly cast the result.
okFlag = static_cast<bool>(s >> myStr);
Note that explicit bool conversion operators will still implicitly convert to bool in contexts where a boolean result is expected, such as the conditional expression in an if statement. That's why the code below still compiles without having to add a cast.
if(s >> myStr) { // here operator bool() implicitly converts to bool
// extraction succeeded
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With