文字列から値を設定するために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は何かがうまくいかなかったと思うのでしょうか?