siplasplas
A library for C++ reflection and introspection
cpp::AssertExpression Class Reference

Implements a siplasplas assertion. More...

#include <siplasplas/utility/assert.hpp>

Public Member Functions

 AssertExpression (bool expressionResult, const std::string &message, const std::string &file, std::size_t line)
 Initializes an assertion expression. More...
 
 ~AssertExpression () noexcept(false)
 Assertion destructor. More...
 
AssertExpressiononFailure (const std::function< void()> &callback)
 Specifies an action to execute when the assertion fails. More...
 

Detailed Description

Implements a siplasplas assertion.

Siplasplas implements assertions as instances of AssertExpression class. An assert expression object takes the result (true or false) of the assertion, its source location (file, line) and a detailed message. The assertion is evaluated during the destruction of the assertion object. If the assertion failed (i.e. the value of the result was false) the AssertExpression destructor throws an AssertException exception.

Constructor & Destructor Documentation

cpp::AssertExpression::AssertExpression ( bool  expressionResult,
const std::string &  message,
const std::string &  file,
std::size_t  line 
)

Initializes an assertion expression.

Parameters
expressionResultResult of the assertion expression evaluation. True if the assertion passed, false if the assertion failed.
messageAsseertion error message.
fileLine where the assertion is defined.
lineFile where the assertion is defined.
cpp::AssertExpression::~AssertExpression ( )
noexcept

Assertion destructor.

The assertion result value is checked in the destructor body. If the result was true the assertion is considered passed and the program continues. If the result is false, the onFailure() callback is called (if any) and then an AssertExpression is thrown with detailed information about the assertion failure (Assertion message, location, etc). The assertion stack trace is logged to the error log (See cpp::exception()).

Member Function Documentation

AssertExpression& cpp::AssertExpression::onFailure ( const std::function< void()> &  callback)

Specifies an action to execute when the assertion fails.

This function allows to install a callback on the assertion so an special action can be taken when the assertion fails. The callback is unique, i.e. two consecutive calls to onFailure() overwrite the assigned callback.

Parameters
callbackFunction to execute when the assertion fails.
Returns
Reference to the assertion expresion (*this). Implements a fluent interface on the assertion expression.
static std::size_t failures = 0;
int sqrt(int n)
{
SIPLASPLAS_ASSERT_BT(n, 0).onFailure([&]
{
// Increment the global failures count
// if the assertion fails.
failures++;
});
return 1 / finvsqrt(n);
}

The documentation for this class was generated from the following file: