C++20 introduced std::source_location
to represent the information about the code point. This class exposes the same information as
__FILE__
, __LINE__
, and __func__
and makes passing this information as a single argument possible.
Furthermore, the std::source_location::current()
function, when used as the default argument of the function parameter, will collect
information from the call site. Consequently, this class enables the replacement of various logging macros, with functions accepting
std::source_location
as a parameter.
This rule reports the use of source location-related macros like __FILE__
, __LINE__
, and __func__
which can
be replaced by std::source_location
.
Noncompliant code example
void log(std::string_view message, std::string_view func, std::uint_least32_t line);
#define TRACE(msg) std::cout << __FILE__ << ':' <<__LINE__ << ' ' << msg // Noncompliant
void func() {
log("entering func", __func__, __LINE__); // Noncompliant
TRACE("leaving func");
}
Compliant solution
void log(std::string_view message, std::source_location loc = std::source_location::current());
std::ostream trace(std::string_view msg,
std::source_location location = std::source_location::current()) {
return std::cout << location.file_name() << ':' << location.line() << ' ' << msg;
}
void func() {
log("entering func");
// or equivalently log("entering func", std::source_location::current());
trace("leaving func");
}