跳到正文

个人记录

一份 print

blue_switch约 6 分钟
原文
文章信息与版本

文章信息

发布
2026年7月31日
收录
2026年11月26日
更新
2026年11月26日
篇幅
约 6 分钟

版本

  1. v1当前

是调 splay 调闹心的时候想要搞的。

大部分是 ds 老师写的。

可以对输出着色,形式类似 python,sep 和 end 之类的参数在模板参数里传入。

C++
#include <string>
#include <iostream>
#include <algorithm>
#include <type_traits>
#ifndef DEBUG_H
#define DEBUG_H
#ifdef DEBUG
namespace debug {
    using std::string;
    using std::copy;
    using std::cout;
    void print() { cout << "\n"; }
    enum colors { _red, _green, _yellow, _blue, _cyan };
    string pre[] = {"\033[1;31m", "\033[1;32m", "\033[1;33m", "\033[1;34m", "\033[1;36m"};
    template <typename T, int color>
    class colored {
        public:
        T val;
        colored(T v) : val(v) {}
        void operator()() const {
            cout << pre[color] << val << "\033[0m";
        }
    };
    template<typename T> using red = colored<T, _red>;
    template<typename T> using green = colored<T, _green>;
    template<typename T> using yellow = colored<T, _yellow>;
    template<typename T> using blue = colored<T, _blue>;
    template<typename T> using cyan = colored<T, _cyan>;
    template <size_t N>
    struct fixed_string {
        char data[N]{};
        constexpr fixed_string() = default;
        constexpr fixed_string(const char (&str)[N]) { std::copy_n(str, N, data); }
        constexpr operator const char*() const { return data; }
    };
    template <typename T>
    void _print(const T& val) { cout << val; }
    template <typename T, int color>
    void _print(const colored<T, color>& c) { c(); }
    template<fixed_string sep = " ", fixed_string end = "\n", typename... Args>
    void print(const Args&... args) {
        bool first = true;
        ((first ? (first = false, _print(args))
                : (cout << (const char*)sep, _print(args))), ...);
        cout << (const char*)end;
    }
}
using debug::red, debug::green, debug::yellow, debug::blue, debug::cyan;
using debug::print;
using debug::colored;
#else
namespace debug {
    using std::string;
    using std::copy;
    enum colors { _red, _green, _yellow, _blue, _cyan };
    template <typename T>
    class colored {
        public:
        T val;
        colored(T v) : val(v) {}
    };
    template<typename T> using red = colored<T>;
    template<typename T> using green = colored<T>;
    template<typename T> using yellow = colored<T>;
    template<typename T> using blue = colored<T>;
    template<typename T> using cyan = colored<T>;
    template <size_t N>
    struct fixed_string {
        char data[N]{};
        constexpr fixed_string() = default;
        constexpr fixed_string(const char (&str)[N]) { std::copy_n(str, N, data); }
        constexpr operator const char*() const { return data; }
    };
    template<fixed_string sep = " ", fixed_string end = "\n", typename... Args>
    void print(const Args&... args) {}
}
using debug::red, debug::green, debug::yellow, debug::blue, debug::cyan;
using debug::print;
using debug::colored;
#endif
#endif
原文