如何连接格式字符串?

How to concatenate the format string?

本文关键字:格式 字符串 连接 何连接      更新时间:2023-10-16

我想连接两个字符串并将它们用作fmt库的格式字符串。 一个明显的选择是简单地将它们连接为常规字符串,然后将它们传递到库中:

template<typename... Args>
inline void catfmt(std::string a, std::string b, const Args &... args) {
std::string c = a+b;
fmt::print(c, args...);
}

但是,c将被丢弃。所以也许 fmt 提供了一种完全跳过它的方法?有没有办法将字符串放入消息中并告诉库它也应该被解析?像这样:

template<typename... Args>
inline void catfmt(std::string a, std::string b, const Args &... args) {
fmt::print("{:sf}{:sf}", a, b, args...);
}

{:sf}的意思是:放置一个字符串并将其用作格式。

有没有办法将字符串放入消息中并告诉库它也应该被解析?

没有这样的办法。您必须使用operator+连接它,这是对格式的嵌套调用

fmt::print(fmt::runtime(fmt::format("{}{}", a, b)), args...);

或其他方法。