I've overloaded operator ">>" for an Enum:
#include <iostream>
#include <boost/lexical_cast.hpp>
using namespace std;
enum MyEnum
{
ONE = 0,
TWO,
TREE,
MAX
};
const char* MyEnumString[MAX] =
{
"ONE"
,"TWO"
,"THREE"
};
istream& operator>>(istream& is, MyEnum& myEnum)
{
string value;
is >> value;
myEnum = ONE;
for (int i=0; i < MAX; i++)
{
if (!value.compare(MyEnumString[i]))
{
myEnum = static_cast<MyEnum>(i);
return is;
}
}
return is;
}
int main()
{
cout << "Hello World" << endl;
boost::lexical_cast<MyEnum>(""); //Throws exception.
return 0;
}
The output I'm getting:
Hello World terminate called after throwing an instance of 'boost::exception_detail::clone_impl
' what(): bad lexical cast: source type value could not be interpreted as target
The exception is thrown from lexical_cast_39.hpp (1155):
if (interpreter >> result)
The operator is working for every value except empty string. The input stream that being returned from the operator is the same stream that was from the beginning.
What is the acceptable approach for such issue? Thanks!