std::format with constant inline class member causes "Call to consteval function did not produce a valid constant expression"

18 hours ago 2
ARTICLE AD BOX

Your Constants::SPECIAL_FOLDER_KEY is not a compile-time constant expression, hence the error. At compile-time, std::basic_format_string expects to be constructed from a string literal directly, or at least a string type that can be used in a constant expression, which std::wstring cannot (unless the compiler implements an extension that allows short strings using SSO to avoid allocating memory at compile-time):

class Constants { public: //... inline static const std::wstring SPECIAL_FOLDER_KEY = L"<FOLDER-SPECIAL-{}>"; }; std::format(Constants::SPECIAL_FOLDER_KEY, folderName); // fails std::format(L"<FOLDER-SPECIAL-{}>", folderName); // OK

What you can do, however is use a constexpr std::wstring_view or a constexpr wchar_t[] instead of std::wstring:

class Constants { public: //... inline static constexpr std::wstring_view SPECIAL_FOLDER_KEY = L"<FOLDER-SPECIAL-{}>"; }; class Constants { public: //... inline static constexpr wchar_t SPECIAL_FOLDER_KEY[] = L"<FOLDER-SPECIAL-{}>"; };

Either of those will work just fine with std::basic_format_string.

If you must use a std::wstring for your constant then you will need C++26, where you can use std::runtime_format() to convert a std::wstring (or wchar_t*) to a std::basic_format_string at runtime instead of at compile-time:

std::format(std::runtime_format(Constants::SPECIAL_FOLDER_KEY), folderName);

If you can't use C++26 yet, then you will have to use std::vformat() instead:

std::vformat(Constants::SPECIAL_FOLDER_KEY, std::make_wformat_args(folderName));
Read Entire Article