Question Details

No question body available.

Tags

c++ gcc format string-literals c++23

Answers (1)

June 10, 2026 Score: 2 Rep: 5,247 Quality: Low Completeness: 80%

You can use std::tochars which is constexpr since C++23 (https://en.cppreference.com/cpp/utility/tochars). But it won't be enough. Compile-time concatenation is not straightforward.

It cannot be achieved from std::stringview for reasons explained there: Concatenating stringview objects.

It does not always work with std::string because it dynamically allocates its data. Thus it can be only used if the string is destroyed at the end of the constexpr expression. It can accidentally work if Short String Optimization applies but it is implementation and data dependant.

So the issue is a bit more complex than it seems.

First of all, I will propose a user-defined compile-time string literal, with well defined concatenation.

This can be done like this:

#include

// LiteralString is a literal class type, usable as constant template parameter // N does not includes null final character template struct LiteralString { consteval LiteralString(const char* s) { std::copy(s, s + N, &data[0]); } consteval operator std::stringview() const { return {data, N}; }

static constexpr std::sizet size = N; char data[N]{}; };

// deduction guide for string literals template LiteralString(const char (&s)[N]) -> LiteralString;

// user-define string litteral template constexpr auto operator""ls() { return LS; }

// compile-time only concatenation template consteval auto operator+(LiteralString const& lhs, LiteralString const& rhs) { constexpr std::sizet NewSize = Ln + Rn; char data[NewSize]{}; auto ptr = std::copy(lhs.data, lhs.data + Ln, &data[0]); std::copy(rhs.data, rhs.data + Rn, ptr); return LiteralString{data}; }

Note that I will need to construct from const char* s later, which does not allow to deduce N. If I want to initialize from a simple string literal such as "Hello" I will have to deduce N from the string length and I achieve that through a deduction guide.

Then lets work on the creation from a number, using std::tochars:

namespace Details { // number of digits of i in base 10 template consteval std::size_t NbDigits() { if constexpr (i