我可以使用包含语法的 const char* 或 std::string 变量作为 libfmt 的参数吗?

Can I use a const char* or std::string variable containing grammar as argument to libfmt?

希望这是一个愚蠢的问题。我有以下代码:

#include <iostream>
#include <fmt/format.h>
#include <string>
int main(){
 double f = 1.23456789;
 std::cout << fmt::format( "Hello {:f} how are you?\n", f ) << "\n";
 return 0;
}

这按预期工作 --你好 1.234568 你好吗?

但是如果我想把传给fmt::format的字符串封装成一个变量,我运行就编译报错了:

#include <iostream>
#include <fmt/format.h>
#include <string>
int main() {
 double f = 1.23456789;
 const char* m = "Hello {:f} how are you?\n"; //can't be constexpr, generated at run time
 std::cout << fmt::format( m, f ) << "\n";
 return 0;
}

但是,在使用 #include <format> 的 MSVC 2022 上,这非常有效...

#include <iostream>
//#include <fmt/format.h>
#include <format>
#include <string>
int main() {
 double f = 1.23456789;
 const char* m = "Hello {:f} how are you?\n";
 std::cout << std::format( m, f ) << "\n";
 return 0;
}

这可以使用 libfmt 吗?看起来 libfmt 想要传入一个 constexpr 值,而 msvc 的 <format> 在 运行 时评估它。我在这里犯了什么愚蠢的错误?

从 libfmt 8.1 开始,您可以将格式字符串包装在 fmt::runtime 中以启用运行时格式:

#include <iostream>
#include <fmt/format.h>
#include <string>
int main() {
 double f = 1.23456789;
 const char* m = "Hello {:f} how are you?\n"; //can't be constexpr, generated at run time
 std::cout << fmt::format(fmt::runtime(m), f ) << "\n";
 return 0;
}

您可以将 fmt::vformat 用于 run-time 字符串

#include <iostream>
#include <fmt/format.h>
#include <string>
int main() {
 double f = 1.23456789;
 const char* m = "Hello {:f} how are you?\n"; //can't be constexpr, generated at run time
 std::cout << fmt::vformat( m, fmt::make_format_args(f)) << "\n";
 return 0;
}

Demo

Is this possible using libfmt? It appears libfmt wants a constexpr value passed in whereas msvc's evaluates this at runtime.

P2216R3 makes std::format only accept compile-time format string. If you want to use run-time format string you need to use std::vformat。我怀疑这只是因为 MSVC 还没有实现 P2216R3。