Debug in C++

Правка en5, от zenny0212, 2025-05-30 09:53:26

Tired of typing cout more than actual logic? Try this macro. It lets you debug anything (just override << first).

Works for almost every C++ type. Side effects may include cleaner code and sudden confidence in debugging.

//*** debug(x) ***//
#define DEBUG 1

#if DEBUG
#define del cout << '\n'
#define debug(...) _debug(#__VA_ARGS__, __VA_ARGS__)
template <class X, class Y>
ostream& operator<<(ostream& os, pair<X, Y> const& p) {
    return os << "(" << p.first << ", " << p.second << ")";
}
template <class Ch, class Tr, class Container>
basic_ostream<Ch, Tr>& operator<<(basic_ostream<Ch, Tr>& os, Container const& x) {
    int i = 0, n = (int) distance(x.begin(), x.end());
    os << "{ ";
    for (const auto& y : x) os << y << (++i < n ? ", " : "");
    return os << " }";
}
template <typename... Args>
void _debug(const char* names, Args&&... args) {
    string_view s(names);
    cout << "{ ";
    size_t i = 0, cnt = 0, n = sizeof...(args);
    auto next = [&]() {
        while (i < s.size() && (s[i] == ' ' || s[i] == ',')) ++i;
        size_t st = i;
        while (i < s.size() && s[i] != ',') ++i;
        return s.substr(st, i - st);
    };
    ((cout << next() << ": " << args << (++cnt < n ? ", " : "")), ...);
    cout << " }" << '\n';
}
#else
#define del
#define debug(...)
#endif
Full debug code
Output of full debug code

Drop a comment if you agree—or if you’ve got a genius idea you’re hiding!

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en7 Английский zenny0212 2025-11-23 17:11:40 53 Tiny change: ' hiding!\n' -> ' hiding!\n\nUpdate: It works with C++11 or newer C++ versions\n'
en6 Английский zenny0212 2025-11-23 17:09:58 214
en5 Английский zenny0212 2025-05-30 09:53:26 12
en4 Английский zenny0212 2025-05-30 05:52:02 3168
en3 Английский zenny0212 2025-05-28 18:30:39 3
en2 Английский zenny0212 2025-05-28 18:28:41 0 (published)
en1 Английский zenny0212 2025-05-28 18:28:12 7023 Initial revision (saved to drafts)