【发布时间】: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]'
用+ 替换<< 也无济于事
error C2110: '+': cannot add two pointers
【问题讨论】:
-
我怀疑即使编译器内联函数,您传递的参数仍将优先并首先被评估,就好像它被包裹在括号中(确实如此)。不要认为有办法用函数来做到这一点。
-
请注意,您不能完全等效于宏 - 最大的区别是始终针对函数而不是宏评估参数,这对于生产代码可能是显着差异。
-
我可能只是创建一个
std::ostream&,在调试版本中是std::cout,在发布版本中是noop stream。 -
或者,将函数制作成可变参数模板,并将每个东西作为单独的参数传递,而不是让调用者合并它们