Re: Verify and expression
Andrei Alexandrescu (See Website For Email) posted:
bool ok = verify( start_bus() );
I prefer this:
bool ok = start_bus();
assert(ok);
, as it separates the "actual" code from the "debugging" code.
That introduces a gratuitous variable. if (!start_bus()) assert(false);
would avoid that.
The original code contained such a variable, so I took the liberty of
presuming it had a purpose. There's not much merit in writing "assert
(false)", as your error message will simply describe the error as "false"
rather than "start_bus()".
Essentially, I think the OP wants a function/macro that works exactly like
assert, except that it still evaluates its argument when in Release Mode.
Furthermore, I think the OP wants to retain the value of the expression. The
following might be a start:
#include <iostream>
#include <ostream>
#include <cstdlib>
template<class T>
T const &Verify(T const &expr,char const *const str)
{
if(!expr)
{
std::cerr << "VERIFY Failure. \"" __FILE__ "\": Line "
<< __LINE__ << " -- " << str << std::endl;
exit(EXIT_FAILURE);
}
return expr;
}
template<class T>
T &Verify(T &expr,char const *const str)
{
return const_cast<T&>(
Verify(const_cast<T const&>(expr),str)
);
}
#define VERIFY(expr) (Verify((expr),#expr))
class MyClass {
public:
MyClass() {}
operator double() const { return 56.8; }
operator bool() const { return false; }
};
int main()
{
MyClass obj;
double val = VERIFY(obj);
MyClass &r = VERIFY(obj);
std::cout << val << std::endl;
}
--
Frederick Gotham
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]