I would like to implement a CHECK()
function that can work like this:
int a = 1;
int b = 2;
int c = 1;
CHECK(a == b) << "check failed" << endl; // this will abort the program and print "check failed"
CHECK(a == c) << "check failed" << endl; // this will do nothing since CHECK is valid
I do not know how could I abort the program but still print out something. Do you know how to implement some function that works like this?
Completing @DominikKaszewski 's answer
For io-manipulator as std::endl
check&& operator<<(std::ostream& (*manip)(std::ostream&)) && {
if (!success) {
manip(s);
}
return std::move(*this);
}
Avoid side effect when check passes.
#define CHECK(predicate) (predicate) ? check{ true } : check{ false }
Profiting than <<
has higher priority than :
.
So condition ? stream1 : stream2 << "text";
is parsed as
condition ? stream1 : (stream2 << "text");
Fix compilation
check(check&&) = default;
as we use it explicitly :-)
Final code is:
class check {
public:
explicit check(bool success) : success{ success } {}
~check() {
if (!success) {
abort_with_message(s.str());
}
}
check(const check&) = delete;
check(check&&) = default;
check& operator=(const check&) = delete;
check& operator=(check&&) = delete;
template <typename T>
check&& operator<<(const T& value) && {
if (!success) {
s << value;
}
return std::move(*this);
}
check&& operator<<(std::ostream& (*manip)(std::ostream&)) && {
if (!success) {
manip(s);
}
return std::move(*this);
}
private:
bool success{};
std::stringstream s{};
};
#define CHECK(predicate) (predicate) ? check{ true } : check{ false }