尝试封装为函数
我们以函数默认参数的形式来进行封装,可以写出形如下面的代码:
#include <iostream>
#include <string>
void debug_log(const std::string& msg
, const char* const file = __FILE__
, const char* const fun = __func__
, const int line = __LINE__
) {
printf("Debug:[File:%s][Fun:%s][Line:%d] %s", file, fun, line, msg.c_str());
}
int main() {
debug_log("use debug log\n");
}
将这段代码在各种编译其中尝试会因为 const char* const fun = func 产生各种七七八八的错误都会出现:
- 直接无法编译
- 编译运行成功,但是会报警告
- 运行打印垃圾数据
- 运行打印空串

原因主要在于 warning: 'func' is not defined outside of function scope。也就是说 func 仅在函数体内可用。
并且 LINE 所替换成的常量也是在函数的参数位置的行号。
因此这种方式无法满足我们的需求。