我可以使用包含语法的 const char* 或 std::string 变量作为 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;
}
这按预期工作 --Hello 1.234568 how are you?
但是,如果我想将传递到 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;
}
但是,在 MSVC 2022 上使用 #include
,这可以完美地工作......
#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 的
在运行时对此进行评估。我在这里犯了什么愚蠢的错误?
Hopefully this is a silly question. I have the following code:
#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;
}
And this works as expected --Hello 1.234568 how are you?
But if I want to encapsulate the string passed into fmt::format as a variable, I run into a compiler error:
#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;
}
However, on MSVC 2022 using #include <format>
, this works perfectly...
#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;
}
Is this possible using libfmt? It appears libfmt wants a constexpr value passed in whereas msvc's <format>
evaluates this at runtime. What silly mistake am I making here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从 libfmt 8.1 开始,您可以将格式字符串包装在
fmt::runtime
< /a> 启用运行时格式化:Since libfmt 8.1, you can wrap the format string in
fmt::runtime
to enable runtime formatting:您可以对运行时字符串使用
fmt::vformat
Demo
P2216R3 使
std::format
仅接受编译时格式字符串。如果要使用运行时格式字符串,则需要使用std ::vformat
。我怀疑这只是因为 MSVC 尚未实现 P2216R3。You can use
fmt::vformat
for run-time stringDemo
P2216R3 makes
std::format
only accept compile-time format string. If you want to use run-time format string you need to usestd::vformat
. I suspect this is just because MSVC has not implemented P2216R3 yet.