C++ 用函数替换日志宏

C++ 用函数替换日志宏,c++,function,macros,c++17,C++,Function,Macros,C++17,我有以下宏定义: #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 函数参数的第一部分必须是可用于标准流的定义良好的类型,例如: std::string tes

我有以下宏定义:

#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

函数参数的第一部分必须是可用于标准流的定义良好的类型,例如:

std::string testVariable = "test";
LOG(std::string("This is a Test message") + " with " + testVariable + " a variable");
在的帮助下,我将函数设置为vararg模板,并简单地使用参数包

模板
内联无效日志(常量T&…x){
if constexpr(DebugBuild){

(std::我是否可以怀疑,即使编译器内联函数,您传递的参数仍将优先并首先求值,就像它被包装在括号中一样(实际上是这样的)。不要认为有一种方法可以用函数实现这一点。请注意,您不能完全等效于宏-最大的区别是,参数总是针对函数而不是宏进行计算,这可能是生产代码的显著区别。我可能只需要做一个
std::ostream&
在调试构建中是
std::cout
,并且在发布版本中是一个。或者,将函数制作成一个vararg模板,并将每个内容作为单独的参数传递,而不是让调用方合并它们
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");
logD("This is a ","test with a ",variable," variable");