C++ Logo


Advanced search

source_location improvement

From: Mike <mike_at_[hidden]>
Date: Wed, 28 Apr 2021 20:30:10 +0100

Before the introduction of source_location one would do something like:

#define STRINGIFY_IMPL(x) #x
#define LOG(msg) std::cerr << __FILE__ "(" STRINGIFY(__LINE__) "):" <<
msg << std::endl;

The thing to note here is the msg prefix is created at compile time, the
compiler is just concatenating adjacent string literals.

With source_location, even though it returns constexpr, you can't do
this. It feels frustrating that all the info is there but you can't
easily create a compile time string like you can with macros.

Given that source_location is a magic class built into the compiler,
could the "current" member function take a format string, and add a new
member function:

     constexpr const char* c_str() const noexcept;

So one could now do something like:

void log(const char* msg, std::source_location loc =
source_location::current("%f(%l): "))
     std::cerr << loc.c_str() << msg << std::endl;

And this would then all be magically worked out at compile time just
like the macro version.


Received on 2021-04-28 14:30:17