用函数替换日志记录宏
Replace logging macro with function
我有如下宏定义:
#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::string testVariable = "test";
LOG(std::string("This is a Test message") + " with " + testVariable + " a variable");
在 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");
我有如下宏定义:
#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::string testVariable = "test";
LOG(std::string("This is a Test message") + " with " + testVariable + " a variable");
在 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");