【问题标题】:Replace logging macro with function用函数替换日志记录宏
【发布时间】:2020-07-16 19:04:32
【问题描述】:

我有以下宏定义:

#if DEBUG
#include <iostream>
#include <ostream>
#define LOG(x) std::cout << x << std::endl;
#else 
#define LOG(x) // LOG(x) is replaced with nothing in non-debug
#endif

一个等效的函数看起来如何允许这样做?:

LOG("This is a Test message" << " with " << testVariable << " a variable");

我当前的实现如下所示:

template <typename T>
inline void logD(const T& x) {
    if constexpr (Debug) {
        std::cout << x << std::endl;
    }
};

但我收到以下错误:

error C2296: '<<': illegal, left operand has type 'const char [25]'

+ 替换&lt;&lt; 也无济于事

 error C2110: '+': cannot add two pointers

【问题讨论】:

  • 我怀疑即使编译器内联函数,您传递的参数仍将优先并首先被评估,就好像它被包裹在括号中(确实如此)。不要认为有办法用函数来做到这一点。
  • 请注意,您不能完全等效于宏 - 最大的区别是始终针对函数而不是宏评估参数,这对于生产代码可能是显着差异。
  • 我可能只是创建一个std::ostream&amp;,在调试版本中是std::cout,在发布版本中是noop stream
  • 或者,将函数制作成可变参数模板,并将每个东西作为单独的参数传递,而不是让调用者合并它们

标签: c++ function macros c++17


【解决方案1】:

Mooing_Duck 的帮助下,我将该函数设为可变参数模板并简单地使用参数包。

template <typename ...T>
inline void logD(const T&... x) {
    if constexpr (DebugBuild) {
        (std::cout << ... << x) << std::endl;
    }
};

你用逗号分隔的内容调用函数。

logD("This is a ","test with a ",variable," variable");

【讨论】:

    【解决方案2】:

    函数参数的第一部分必须是可以与标准流一起使用的明确定义的类型,例如:

    std::string testVariable = "test";
    LOG(std::string("This is a Test message") + " with " + testVariable + " a variable");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-10
      • 2011-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-30
      • 2013-11-22
      相关资源
      最近更新 更多