mardi 26 janvier 2016

C++ Custom Assert

I am trying to write my own custom assert for my own project. This project will be written with c++11.

The assert must have the following qualities:

It must be kept as an expression and is assignable. E.g. I should be able to write code like this int x = custom_assert(1/y);

It must be overloaded to accept an assert with a message and without one. E.g int x = custom_assert(1/y, "Error divide by zero"); This code and the above are both compilable and acceptable.

It must have no side-effects in release mode E.g. int x = custom_assert(1/y); will become int x = 1/y; in release mode.

And most importantly, it must break at the specific point where the assert was made. Which will make use of __debugbreak() as part of its evaluating expression.

The following is my attempt:

#include <string>

bool DoLog(std::string msg, std::string file, int line); //Prints to std::cerr and returns HALT macro


#if defined(_DEBUG) || defined(DEBUG)
#define HALT true
#define NT_ASSERT_BASE(x, msg) (!(x) && DoLog((msg), __FILE__, __LINE__) && (__debugbreak(),1))
#else
#define HALT false
#define NT_ASSERT_BASE(x,msg) (x)
#endif//debug/release defines

//--- Can't implement these until I can return the expression ---
//#define GET_MACRO(_1,_2,_3,NAME,...) NAME
//#define FOO(...) GET_MACRO(__VA_ARGS__, FOO3, FOO2)(__VA_ARGS__)

#define NT_ASSERT(expression, msg) NT_ASSERT_BASE(expression,msg)

As you can see my custom assert fails on 2 fronts, namely being kept as expression and assignable, and on overloading (Which I cannot implement until I figure out how to keep it as an expression.

All in all, I may be chasing stars and this macro may in fact be impossible to make. (Which I hope isn't the case)

Many thanks.

Aucun commentaire:

Enregistrer un commentaire