如何将非可变参数值传递给 fmt::format?
How to pass not variadic values to fmt::format?
我正在使用很棒的 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_args
或fmt::wformat_args
对象,但创建format_args
或wformat_args
对象的唯一方法是通过另一个可变参数函数,这意味着参数的数量和类型必须在编译时知道。
所以你可以写一个包装器来解压缩一个std::tuple
或std::array
并将其元素传递给fmt::format
,因为这些元素的数量和类型在编译时是已知的。 但是你不能对std::vector
、std::list
等做同样的事情,因为这些容器的大小在运行时可能会有所不同。
相关文章:
- 为什么可以将左值传递给"std::async",即使它引用了右值
- 当值传递给C++中的运算符重载函数时会发生什么
- 如何将非可变参数值传递给 fmt::format?
- 将 qml 项目值传递给 cpp 后如何与它们进行交互?
- NDK:将文本字段值传递给 c++ 字符串
- 如何将值传递给 lambda 函数
- 如何在C++中将std::string值传递给RegSetValueEx()
- 如何将 c ++ 变量的值传递给 hadoop HDFS 的 bash 系统命令?
- C++ 通过参数将值传递给 char 数组
- 如何将值传递给MFC消息映射函数on_command
- 使用JNI将长值传递给Java
- 如何在不使用 Argv 和 Argc 的情况下将 Sum 值传递给 C++ 程序
- C++ 将值传递给 fStream
- 如何将函数中的多个值传递给C++中的不同函数
- 将多个解析值传递给 addPositionalArgument 函数
- C++为什么将左值传递给move构造函数对模板有效
- 一种自动检测对象的方法,该方法通过值传递给c++中的函数
- 将值传递给main(int,char**)
- 将大于long类型的最大值的值传递给C中的fseek
- 将值传递给atexit