通常来说,在打印日志时为了获取调用处的相关信息,传统做法都需要定义一个宏来收集相关信息。
但是借由C++20的std::source_location,我们可以实现一个无宏定义的日志打印函数。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
| #include <iostream>
#include <format>
#include <source_location>
#include <string_view>
namespace Logger {
struct FormatWithLocation {
std::string_view value;
std::source_location loc;
template <typename String>
FormatWithLocation(const String& s, const std::source_location& l = std::source_location::current())
: value{s}, loc{l}
{}
};
template <typename... Args>
void Debug(FormatWithLocation fmt, Args &&...args)
{
std::string formattedMessage = std::vformat(fmt.value, std::make_format_args(std::forward<Args>(args)...));
std::cout << "[" << fmt.loc.file_name() << ":" << fmt.loc.line() << "] " << formattedMessage << std::endl;
}
} // namespace Logger
int main()
{
int num = 123;
Logger::Debug("test {}", num);
return 0;
}
|
编译运行:
1
| g++ main.cc -Wall -o main && ./main
|
预期输出: