C++ Logo

std-proposals

Advanced search

Re: source_location improvement

From: Edward Catmur <ecatmur_at_[hidden]>
Date: Wed, 5 May 2021 23:25:34 +0100
On Wed, 5 May 2021 at 22:06, Mike via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> How do we "allow compile-time string processing"?
>

By making std::format constexpr:

template<class... Args>
constexpr std::string format(std::string_view fmt, const Args&... args);
^~~~~~~~~

Note that std::string is already constexpr since C++20.

So, taking my specific problem, given `loc` returned by
> source_location::current(), how do we use loc.file_name() (returning
> constexpr const char*) and loc.line() (returning constexpr
> unint_least32_t) to create a single compile time string like
> "foo.cpp(555): beyond all recognition"? Could you give me an example of
> the kind of syntax you were thinking of?
>

constexpr auto locf = std::format("{}({}): ", loc.file_name(), loc.line());

Currently the problem is that a constexpr allocation can't escape constexpr
evaluation (as Jason mentions above re. "non-transient allocations"), so
you'll have to do something silly like https://godbolt.org/z/c67Tzj4oc :

constexpr auto locff = [&] { return std::format("{}({}): ",
loc.file_name(), loc.line()); };
constexpr auto locf = static_string<locff().size()>(locff().c_str());

On the other hand, if your source filenames are reasonably short you might
be able to get away with using the SSO buffer. For a while, anyway.

Are there already proposals for this kind of compile time string
> composition from constexpr expressions?
>

I'm not aware of any. P2216 is focussing on (compile time) safety, mainly.

Received on 2021-05-05 17:25:47