Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* This header file defines a macro that works the same way as assert()
- * from assert.h, except that it also allows specifying expressions
- * whose values will be output alongside the failed assertion.
- * Error messages will be output to std::cerr
- * and the program terminated with std::terminate().
- *
- * Usage:
- * assertpp(condition, [<expression> [...]]);
- *
- * Examples:
- * assertpp(x<4);
- * assertpp(x==4, x);
- * assertpp(vec.size() < limit, limit, vec.size());
- * assertpp(var1==var2, var1, var2);
- *
- * Copyright: (C) 2015 Joel Yliluoma, http://iki.fi/bisqwit/
- * License: Creative Commons Attribution (CC-BY 1.0, 2.0 or 3.0)
- */
- #include <iostream>
- #include <exception>
- #ifdef NDEBUG
- #define assertpp(condition, args...)
- #else
- template<typename...>
- class assertpphandler
- {
- const char* v;
- public:
- assertpphandler(const char condstr[], const char file[], unsigned line, const char func[], const char* vars) : v(vars)
- {
- std::cerr << file << ':' << line << ": " << func << ": Assertion failed: " << condstr << " (";
- if(*v) std::cerr << "With ";
- }
- void operator() () { std::cerr << ")\n"; std::terminate(); }
- template<typename T, typename...U> void operator()(T&& v, U&&... rest)
- {
- GetVar() << std::forward<T>(v);
- (*this)(std::forward<U>(rest)...);
- }
- private:
- std::ostream& GetVar()
- {
- int parens=0;
- if(*v == ',') { std::cerr << ", "; ++v; }
- while(*v == ' ' || *v == '\t' || *v == '\n' || *v == '\r' || *v == '\v') ++v;
- while(*v && (*v != ',' || parens != 0))
- {
- if(*v == '(') ++parens; else if(*v == ')') --parens;
- std::cerr << *v++;
- }
- return std::cerr << " = ";
- }
- };
- #ifdef __GNUC__
- # define assertpp(condition, ...) do { \
- if(__builtin_expect(!(condition),false)) \
- assertpphandler<>(#condition, __FILE__, __LINE__, __PRETTY_FUNCTION__, #__VA_ARGS__)(__VA_ARGS__); } while(0)
- #else
- # define assertpp(condition, ...) do { \
- if(!(condition)) \
- assertpphandler<>(#condition, __FILE__, __LINE__, __func__, #__VA_ARGS__)(__VA_ARGS__); } while(0)
- #endif
- #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement