assert.cpp

(plain text)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <stdexcept>
#include <string>
#include <cassert>

#ifndef NDEBUG
#  undef   assert
#  define  assert(test)             assert2(test, __FILE__, __LINE__)
#  define assert2(test, file, line) assert3(test, file,     line)

inline void throwing_assert (bool test, const std::string &msg) {
  if (!test) throw std::logic_error(msg);
}

#  if (__GNUC__ == 2 && __GNUC_MINOR__ >= 6) || __GNUC__ > 2

#    define assert3(test, file, line)                    \
     (::throwing_assert(test,                            \
                        std::string(file ":" #line ": ") \
                        .append(__PRETTY_FUNCTION__)     \
                        .append(": assertion '" #test "' failed.")))

#  else

#    define assert3(test, file, line) \
     (::throwing_assert(test,         \
                        file ":" #line ": assertion '" #test "' failed."))

#  endif

#endif

#include <iostream>

int main () try {
  assert(0 == 1);
}

catch (const std::exception &e) {
  std::cerr << "exception: " << e.what() << '\n';
}