如何将非可变参数值传递给 fmt::format?

How to pass not variadic values to fmt::format?

本文关键字:fmt 值传 format 参数 变参      更新时间:2023-10-16

我正在使用很棒的 fmt C++ 库来更优雅地格式化字符串。

我想将一个非变量参数列表传递给fmt::format.它可以是std::vector,或std::string,或其他什么,但它将始终与格式字符串匹配。

所以fmt::format的工作方式是这样的:

std::string message = fmt::format("The answer is {} so don't {}", "42", "PANIC!");

但我想要的是这样的:

std::vector<std::string> arr;
arr.push_back("42");
arr.push_back("PANIC!");
std::string message = fmt::format("The answer is {} so don't {}", arr);

有没有办法/解决方法?

您可以从vector自行构建参数以vformat。这似乎有效:

std::string format_vector(std::string_view format,
std::vector<std::string> const& args)
{
using ctx = fmt::format_context;
std::vector<fmt::basic_format_arg<ctx>> fmt_args;
for (auto const& a : args) {
fmt_args.push_back(
fmt::internal::make_arg<ctx>(a));
}
return fmt::vformat(format,
fmt::basic_format_args<ctx>(
fmt_args.data(), fmt_args.size()));
}
std::vector<std::string> args = {"42", "PANIC!"};
std::string message = format_vector("The answer is {} so don't {}", args);

添加一个额外的图层,如下所示:

template <std::size_t ... Is>
std::string my_format(const std::string& format,
const std::vector<std::string>& v,
std::index_sequence<Is...>)
{
return fmt::format(format, v[Is]...);
}

template <std::size_t N>
std::string my_format(const std::string& format,
const std::vector<std::string>& v)
{
return my_format(format, v, std::make_index_sequence<N>());
}

用法将是:

std::vector<std::string> arr = {"42", "PANIC!"};
my_format<2>("The answer is {} so don't {}", arr);

使用operator ""_format,您可能会在编译时获得有关预期大小的信息

在当前版本(8.1.1)中,可以执行以下操作;

fmt::dynamic_format_arg_store<fmt::format_context> ds;
ds.push_back(42);
ds.push_back("PANIC");
std::string msg = fmt::vformat("The answer is {} so don't {}", ds);

如果不对 fmt 库进行更改,这似乎是不可能的。fmt::format调用fmt::vformat,它接受表示多个参数的fmt::format_argsfmt::wformat_args对象,但创建format_argswformat_args对象的唯一方法是通过另一个可变参数函数,这意味着参数的数量和类型必须在编译时知道。

所以你可以写一个包装器来解压缩一个std::tuplestd::array并将其元素传递给fmt::format,因为这些元素的数量和类型在编译时是已知的。 但是你不能对std::vectorstd::list等做同样的事情,因为这些容器的大小在运行时可能会有所不同。