V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
sbldehanhan
V2EX  ›  C++

如何在 C++中实现这个效果?

  •  
  •   sbldehanhan · 90 天前 · 1839 次点击
    这是一个创建于 90 天前的主题,其中的信息可能已经有所发展或是发生改变。
    #ifdef DEBUG
    #define dprintf(x...)	printf(x)
    #else
    #define dprintf(x...)
    #endif
    

    如上。上面的这个是用的 printf 函数,在 C++中用有什么负面影响吗?不是说 cout 和 printf 最好不要混用吗?所以,能不能将上面的逻辑用 cout 实现?

    6 条回复    2024-01-30 09:07:14 +08:00
    AFOX
        1
    AFOX  
       90 天前
    用 spdlog 库
    Astor
        2
    Astor  
       89 天前
    C++ 用 printf 没问题啊,甚至性能可能稍微好一点。不过日志打印到 stderr 里面。
    kirory
        3
    kirory  
       89 天前
    class DummyStream{
    public:
    template<typename T>
    DummyStream operator << (const T&) const {
    return * this;
    }
    };


    #ifdef DEBUG
    #define dprintf(x...) std::cout
    #else
    #define dprintf(x...) DummyStream{}
    #endif
    kkk9
        4
    kkk9  
       89 天前
    cpp 要站在巨人的肩膀上,所以 #1 SPDLOG 推荐
    sjkdsfkkfd
        5
    sjkdsfkkfd  
       89 天前
    用 fmt 多好,20 自带,20 之前用 libfmt

    ```
    #ifdef DEBUG
    #define dprintf(...) fmt::print(__VA_ARGS__)
    #else
    #define dprintf(...) static_assert(true,"")
    #endif
    ```
    setname
        6
    setname  
       89 天前
    ```
    #define dprintf(x...) do { \
    int size_s = std::snprintf(nullptr, 0, x) + 1; \
    char* str = new char[size_s]; \
    std::snprintf(str, size_s, x); \
    cout << str << endl; \
    delete []str; \
    } while(0)
    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3570 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 10:42 · PVG 18:42 · LAX 03:42 · JFK 06:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.