c++formatconst-reference

Why std::make_format_args expects a non-const reference


Looking at the documentation, I don't understand why std::make_format_args() takes a reference and not a const reference?

My goal is to implement something like:

#include <format>

template <class... Args>
inline static std::string format(const std::string_view field, Args&&... args)
{ 
    return std::vformat(field, std::make_format_args(std::forward<Args>(args)...)); 
}

And being able to pass const std::string& as input in args, but it seems like std::make_format_args() expects a non-const reference.

I get an error:

A non-const reference may only be bound to an lvalue C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.40.33807\include\format(3713): note: see declaration of 'std::make_format_args'
note: while trying to match the argument list '(_Ty, const std::string, _Ty, _Ty)'

UPDATE

I can reproduce the error here: https://godbolt.org/z/nj763o48r (locally I get the exact same error as above)


Solution

  • Because of the poor user experience and safety issues detailed in Defect Report P2905R2. The issue, (summaries taken from the bottom of the documentation page) was that "make_format_args accepted rvalue arguments by forwarding references", and the resolution was that make_format_args "only takes lvalue references".