Sco*_*ykl 3 c++ format c++20 fmt
希望这是一个愚蠢的问题。我有以下代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
这按预期工作 -你好 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;
}
Run Code Online (Sandbox Code Playgroud)
然而,在 MSVC 2022 上使用#include <format>,这工作得很好......
#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;
}
Run Code Online (Sandbox Code Playgroud)
使用 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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1242 次 |
| 最近记录: |