skip to content

Why does std::format(tmpl, name, lobby) fail to compile when tmpl is a std::string loaded from a config file, and what do you call instead?

level: seniorimportance: should knowfreq 40%

answer

  1. format_string has a consteval constructor
  2. a runtime string is not a constant
  3. the v-prefixed type-erased functions
  4. errors move back to run time
  5. C++26 names a dynamic wrapper

basics

~10 s

std::format's first parameter is a std::format_string whose constructor is consteval, so it only accepts a compile-time constant it can check. For a runtime template call std::vformat(tmpl, std::make_format_args(name, lobby)) and catch std::format_error.

solid answer

~40 s

The first parameter of `std::format` is `std::format_string<Args...>`, and its converting constructor is `consteval`: every call must be evaluated at compile time, where it parses the string against `Args`. A `std::string` read from a file is not a constant expression, so the call is ill-formed, with clang reporting "call to consteval function ... is not a constant expression". For a template known only at run time, use the type-erased API: `std::vformat(tmpl, std::make_format_args(name, lobby))`. `make_format_args` takes its arguments by lvalue reference in the current wording, so pass named variables, not temporaries. The check now happens at run time, so a bad template throws `std::format_error`, and the code must catch it. C++26 adds `std::dynamic_format(tmpl)`, which can be passed straight to `std::format` for the same effect.

code

cpp · 20 lines
cpp
#include <format>
#include <iostream>
#include <string>

std::string load_template() { return "{} joined lobby {:>4}"; }  // e.g. from a config file

int main() {
    std::string tmpl = load_template();
    std::string name = "ana";
    int lobby = 7;
    // std::format(tmpl, name, lobby);   // error: not a constant expression
    std::cout << std::vformat(tmpl, std::make_format_args(name, lobby)) << '\n';

    try {
        std::string broken = "{} joined lobby {:q}";
        std::cout << std::vformat(broken, std::make_format_args(name, lobby)) << '\n';
    } catch (const std::format_error& e) {
        std::cout << "format_error: " << e.what() << '\n';
    }
}

go deeper

for a junior

Recall that std::format wants a string literal, and that std::vformat with std::make_format_args handles a template known only at run time.

for a middle

Explain the consteval std::format_string constructor and why a runtime value can never satisfy it.

for a senior

Show the production handling: format_error moves to run time, so validate templates at load, catch at call sites, and keep checks with format_string wrappers.

for a principal

Set a policy for where runtime templates are allowed at all, such as translations, and how they are validated before release.

## Why the call is rejected `std::format` is declared as: ```cpp template<class... Args> string format(format_string<Args...> fmt, Args&&... args); ``` `std::format_string<Args...>` is an alias for `std::basic_format_string<char, ...>`. Its converting constructor is a `consteval` template. A `consteval` function is an **immediate function**: every call to it must be a constant expression. The standard adds that the constructor's call is not a constant expression unless the string is a valid format string for arguments of types `Args`. Two things follow: 1. A string literal works, and a bad literal (`{:d}` for a string argument, too few arguments, mixed `{}` and `{1}`) is a **compile error**. 2. A `std::string` whose value is only known at run time can never be a constant expression, so passing it is ill-formed even when its contents would be valid. Apple clang 21 with libc++ reports: ``` error: call to consteval function 'std::basic_format_string<char, int>::basic_format_string<std::string>' is not a constant expression ``` ## The history behind it The first C++20 wording took a plain `string_view` and threw `std::format_error` at run time. In 2021 the committee adopted compile-time checking as a fix applied to C++20, so current compilers apply it in `-std=c++20` mode. The C++23 compatibility annex records the consequence: code with errors in format strings, which used to throw, became ill-formed. The same change is why `std::format(tmpl, ...)` with a variable stopped compiling. ## The runtime path: vformat and make_format_args Every formatting function has a **type-erased** sibling that takes the format string as a plain `std::string_view` and the arguments as a `std::format_args` object: ```cpp std::string tmpl = load_template(); // "{} joined lobby {:>4}" std::string out = std::vformat(tmpl, std::make_format_args(name, lobby)); ``` - `std::make_format_args(args...)` packs references to the arguments into a store that `std::format_args` can view. - The current wording takes `Args&...`, so a temporary such as `std::make_format_args(42)` does not compile on libc++. The C++23 text took forwarding references; the change was adopted as a fix, which is why `make_format_args` wants named variables. - `std::vformat_to` is the version that writes to an output iterator. What you lose is the compile-time check. `std::vformat` parses the string while formatting, and if the template is malformed or does not fit the arguments, it **throws `std::format_error`**. The libc++ message for a bad field reads "The format specifier should consume the input or end with a '}'". ## Choosing an approach | Situation | Use | Failure mode | |---|---|---| | Format string is a literal in the code | `std::format("...", args...)` | compile error | | Template comes from a file, translation table or user | `std::vformat(tmpl, std::make_format_args(args...))` | `std::format_error` at run time | | Same, on a C++26 library | `std::format(std::dynamic_format(tmpl), args...)` | `std::format_error` at run time | | Your own function forwarding to `std::format` | take `std::format_string<Args...>` as its parameter | compile error at your caller | ## Production rules for runtime templates - **Validate when loading.** Try each template once with representative dummy arguments when the config is read, and reject the file then, not at three in the morning when the rare message first fires. - **Catch at the call site.** A log or status path that throws `std::format_error` can take the process down; fall back to printing the raw template and the arguments. - **Never let users supply the template unchecked.** A translator's typo becomes an exception; a template asking for more arguments than you pass also throws. - **Do not reach for `std::vformat` just to pass a format string through a wrapper.** Declare the wrapper's parameter as `std::format_string<Args...>` instead, and the check moves to the wrapper's callers. ## The C++26 wrapper **C++26** adds `std::dynamic_format(string_view)`, which returns an object that `basic_format_string` accepts through a non-consteval constructor, so `std::format(std::dynamic_format(tmpl), name, lobby)` compiles and checks at run time. It was proposed as `std::runtime_format` and renamed in 2026. Libraries that shipped it early may still spell it `runtime_format`: Apple clang 21's libc++, for example, has `std::runtime_format` under `-std=c++2c` and no `std::dynamic_format`, while libc++ 23 and libstdc++ in GCC 16.2 declare `std::dynamic_format`. Code that must build everywhere today sticks to `std::vformat`. ## How to explain it in an interview The short version a senior candidate gives: the check is part of the type system, not a library lint. `std::format_string<Args...>` can only be built at compile time, so a literal is verified and a runtime value is refused. When the text genuinely arrives at run time, you opt out explicitly with the `v` functions, or with `std::dynamic_format` on a C++26 library, and you take back the job of handling `std::format_error`.

  • How do you write a logging function that keeps std::format's compile-time check?
    Make it a variadic template whose format parameter is `std::format_string<Args...>`, as in `template<class... Args> void log(std::format_string<Args...> fmt, Args&&... args)`, and pass `fmt` on to `std::format`. The consteval conversion then happens at each call to `log`, so a bad literal fails where it is written. C++23 named `std::format_string` publicly.
  • Why does std::make_format_args(42) not compile on a current library?
    The current wording declares `make_format_args(Args&... args)`, taking lvalue references, because the returned store only refers to the arguments. A temporary would be destroyed before the store is used. Pass named variables, or call `std::vformat` in the same full-expression with variables.

  • Wrapping the std::string in std::string_view makes std::format accept it
  • std::vformat still checks the format string at compile time
  • std::format_string's constructor is constexpr, so it accepts runtime strings
  • A malformed runtime template is silently printed as plain text
  • std::runtime_format is the final C++26 name for the runtime wrapper

Assumes C++20 with the 2021 compile-time format check; std::dynamic_format is C++26 and earlier libraries spell it std::runtime_format.