我正在创建一个原始类型包装器,它可以使用 boost::lexical_cast 从字符串中设置其值。它工作正常,但由于某种原因 std::istream 提取运算符设置了故障位。以下程序打印:
123.45
例外:ios_base::failbit 设置
但是,如果您注释掉“inStream.exceptions(...”这一行,它会起作用并打印:
123.45
123.45
无论您是否使用 unicode 编译,或者如果您使用 int 或 float 作为 ValueType,都没有什么区别,在任何情况下都会设置故障位。
#include <conio.h>
#include <exception>
#include <iostream>
#include <string>
#include <tchar.h>
#include <boost/lexical_cast.hpp>
#if defined(UNICODE) || defined(_UNICODE)
typedef std::wstring StringType;
typedef std::wistream IStreamType;
#else
typedef std::string StringType;
typedef std::istream IStreamType;
#endif
#if 1 // Use float
typedef float ValueType;
#define VALUE_STRING _T("123.45")
#else // Use int
typedef int ValueType;
#define VALUE_STRING _T("123")
#endif
struct Castable {
ValueType m_val;
};
inline IStreamType& operator>> ( IStreamType& inStream, Castable& castable )
{
inStream.exceptions( IStreamType::failbit | IStreamType::badbit );
inStream >> castable.m_val;
return inStream;
}
int _tmain(int argc, _TCHAR* argv[])
{
try{
StringType sVal = VALUE_STRING;
ValueType val;
val = boost::lexical_cast<ValueType>(sVal);
std::cout << val << std::endl;
Castable cst;
cst = boost::lexical_cast<Castable>(sVal);
std::cout << cst.m_val << std::endl;
}catch( std::exception& ex ){
std::cout << "EXCEPTION: " << ex.what() << std::endl;
}
_getch();
return 0;
}
为什么 std::istream 会认为出了问题?