|
|
Darren New <dne### [at] sanrrcom> wrote:
> I saw a bit of a note describing how to use an "assert" and a "check"
> call in some C++. "Assert" would exit the program if it failed, and
> "check" would let the program continue after logging in order to look
> for more failures.
> But the invocation was along the lines of
> assert(x < 10) <<
> "The value x is " << x << " but that's too small";
That's a rather obscure, although clever way of printing error information
in case of assertion failure.
It's actually not obvious how it's implemented, but at least this would
work:
//------------------------------------------------------------------------
#include <iostream>
#include <cstdlib>
class DataOutput
{
const bool doExit;
public:
DataOutput(bool e): doExit(e) {}
~DataOutput()
{
if(doExit)
{
std::cerr << std::endl;
std::exit(1);
}
}
template<typename T>
DataOutput& operator<<(const T& data)
{
if(doExit) std::cerr << data;
return *this;
}
};
#define assert(cond) ((!(cond)) ? \
(DataOutput(true) << __FILE__ << " " << __LINE__ \
<< ": Assertion (" << #cond << ") failed. ") : \
DataOutput(false))
//------------------------------------------------------------------------
The only problem I see with this is that you can't compile this in a
way that completely drops out the operator<< calls and its parameters.
The operator<< calls are *always* performed, even if no assertion failure
happens, and there's no way of compiling the program so that the compiler
would drop those calls.
--
- Warp
Post a reply to this message
|
|