Exception class with shift operator
Hello,
I would like to use a shift operator for storing information
associated to an exception, as follows:
#include <stdexcept>
#include <string>
void foo()
{
double x = 0.0;
unsigned long u = 1;
std::string s("Runtime error detected in ");
// What I would like to do:
throw std::runtime_error() << s << __FUNCTION__ << ":"
<< " The value of x is " << x
<< " and the value of u is " << u;
}
My trivial solution would be creating and using a class like the
following,
instead of std::runtime_error:
#include <exception>
#include <string>
#include <sstream>
namespace ext
{
class runtime_error : public std::exception
{
public:
runtime_error() : my_ss() {}
explicit runtime_error(const std::string& arg) : my_ss(arg) {}
runtime_error(const runtime_error& e) : my_ss(e.what()) {}
runtime_error& operator=(const runtime_error& e)
{
std::string s(e.what());
my_ss.clear();
my_ss << s;
return *this;
}
virtual ~runtime_error() throw() {}
public:
virtual const char* what() const throw()
{ return my_ss.str().c_str(); }
template <typename T> runtime_error& operator<<(const T& v)
{ my_ss << v; return *this; }
private:
std::stringstream my_ss;
};
} // namespace ext
Can you see problems related to this class and its usage for the
purpose mentioned above?
How can I make it better or, are there other possible solutions?
Thanks in advance for your opinions,
eca
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]