Elad Maimoni
Elad Maimoni

Reputation: 4575

Can I call std::format with a consteval std::array as the format string?

I have a consteval std::array that contains a format string:

consteval std::array<char, 3> make_consteval_format_string()
{
    return std::array<char, 3> {'{', '}', '\n'}; // "{}\n"
}

I can convert this array to std::string_view and invoke std::vformat

template<typename Arg>
std::string format_arg(Arg&& arg)
{
    auto fmt_array = make_consteval_format_string(); // "{}\n"
    std::string_view str{ fmt_array.data(), fmt_array.size() }; // I would like to avoid this line
    return std::vformat(str, std::make_format_args(std::forward<Arg>(arg))); // I would like to call std::format
}

This works just fine:

int main()
{
    std::string s1 = format_arg(123);
}

However, the format string is fully known at compile time, its just that I can't figure out if I can somehow convert it to std::format_string and call std::format instead:

template<typename Arg>
std::string format_arg(Arg&& arg)
{ 
    // this is what I wish to do
    return std::format(make_consteval_format_string(), std::make_format_args(std::forward<Arg>(arg)));
}

So can I convert a consteval std::array to something that std::format will accept?

Upvotes: 2

Views: 1733

Answers (1)

vitaut
vitaut

Reputation: 55524

You can call std::format by converting std::array to std::string_view at compile time and passing the latter as a format string:

template<typename Arg>
std::string format_arg(Arg&& arg) {
  static constexpr auto fmt = make_consteval_format_string();
  return std::format(std::string_view(fmt.data(), fmt.size()), arg);
}

https://godbolt.org/z/55d38EfTq

Upvotes: 2

Related Questions