문자열에서 값을 설정하기 위해 boost :: lexical_cast를 사용할 수있는 원시 타입 래퍼를 만듭니다. 그것은 잘 작동하지만, 어떤 이유로 std :: istream 추출 연산자 failbit를 설정합니다. 다음 프로그램을 인쇄 :std :: istream 추출은 명백한 이유없이 failbit를 설정합니다.
123.45
예외 : ios_base :: failbit는
123.45
123.45
그것은 당신이 유니 코드로 컴파일하거나하지 않을 경우 차이가되지 않습니다, 또는 INT를 사용하거나 치형으로 떠 경우 failbit는 어떤 경우에 설정됩니다.
#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이 문제가 있다고 생각합니까?
맞아. 맞아. 따라서 기본적으로 오류를 잡는 것은 lexical_cast의 책임이므로 대상 클래스가 비즈니스가 아닌 일부 실패에 대해 걱정하지 않도록해야합니다. 그리고 lexical_cast는 아무 것도 던지지 않기 때문에 모든 것이 잘됩니다. 난 그냥 "inStream.exceptions (..."줄을 제거해야합니다. – zeroes00