Hey all,
I was taking a look at my stringstream conversion function and I couldn't decide how I want to handle a bad conversions. I used an exception and then in main I would a use a try, catch block to get any exception.
#include <sstream>
#include <exception>
class ConversionException: public std::exception
{
virtual const char* what() const throw()
{
return "Bad Conversion";
}
} convertError;
template<typename To, typename From>
const To Convert(const From & convertFrom)
{
To convertTo;
std::stringstream ss;
ss << convertFrom;
if(ss >> convertTo)
return convertTo;
throw convertError;
}
My question is would it be better to write the function using a bool to single success or failure like
template<typename To, typename From>
bool Convert(const To & convertTo, const From & convertFrom)
{
std::stringstream ss;
ss << convertFrom;
if(ss >> convertTo)
return convertTo;
return false;
}