使用 {fmt} 引用一个字符串

Quote a string using {fmt}

有什么方法可以使用 {fmt} 打印引用的字符串吗?

这是一个示例代码,展示了我想要实现的目标:

fmt::print("Hello {}!", "Terens");

我希望代码打印 Hello "Terens"! 而不仅仅是 Hello Terens!

编辑:我想使用 API 来打印事先不知道的不同数据(我正在为一个图书馆写这个,所以当数据是 std::string 时我特别想要一个带引号的输出或 std::string_view.

您可以在格式字符串中将“{}”括在引号中或使用 std::quoted. For example (https://godbolt.org/z/f6TTb5):

#include <fmt/ostream.h>
#include <iomanip>

int main(){
  fmt::print("Hello {}!", std::quoted("Terens"));
}

输出:

Hello "Terens"!

I want to use the API for printing different data not known beforehand (I am writing this for a library, so I specifically want a quoted output when the data is a std::string or std::string_view.

以下代码:

#include <fmt/core.h>

template<typename T>
const T& myprint_get(const T& t) {
    return t;
}
std::string myprint_get(const std::string& t) {
    return "\"" + t + "\"";
}

template<typename ...T>
void myprint(const char *fmt, T... t) {
    fmt::print(fmt, myprint_get(t)...);
}

int main() {
    myprint("{} {}", std::string("string"), 5);
}

outputs:

"string" 5

它应该足以让您入门。