[英]format boost multiprecision cpp_int with fmt
我正在嘗試使用 fmt 庫格式化 boost 多精度 cpp_int。
這是我試過的代碼
using boost::multiprecision::cpp_int;
int main() {
cpp_int v("0x8FFFFFFFFFFFFFFFF");
std::string buffer;
fmt::format_to(std::back_inserter(buffer),"{}", v);
std::cout << buffer;
}
https://godbolt.org/z/M4zKc5hr6使用 boost 1.73,fmt 9.1,gcc 7.3
我收到編譯錯誤:
錯誤:static 斷言失敗:無法格式化參數。 使類型 T 可格式化提供格式化程序專業化
我偶然發現這個問題https://github.com/fmtlib/fmt/issues/918似乎已經解決了,所以我期待 fmt 能夠格式化提升多精度數字。 我還需要編寫格式化程序專業化嗎?
您需要提供格式化程序。 例如,您可以選擇加入 ostream 格式化程序:
template <> struct fmt::formatter<cpp_int> : fmt::ostream_formatter {};
現場演示: Live On Coliru
#include <boost/multiprecision/cpp_int.hpp>
#include <fmt/format.h>
#include <fmt/ostream.h>
using boost::multiprecision::cpp_int;
template <> struct fmt::formatter<cpp_int> : fmt::ostream_formatter {};
int main() {
cpp_int v("0x8FFFFFFFFFFFFFFFF");
std::string buffer;
fmt::format_to(std::back_inserter(buffer), "Hello world: {}", v);
fmt::print("Print directly: {} (buffer: {})", v, buffer);
}
輸出:
Print directly: 166020696663385964543 (buffer: Hello world: 166020696663385964543)
演示一個簡單的自定義格式化程序,它使用所需的格式化參數調用i.str(...)
:
#include <boost/multiprecision/cpp_int.hpp>
#include <fmt/format.h>
using boost::multiprecision::cpp_int;
template <> struct fmt::formatter<cpp_int> {
uint8_t showbase_ : 1 = 0, hex_ : 1 = 0, upper_ : 1 = 0;
auto constexpr parse(auto& ctx) {
auto e = std::find(ctx.begin(), ctx.end(), '}');
if (std::string_view f{ctx.begin(), e}; f == "#x")
showbase_ = hex_ = true;
else if (f == "#X")
showbase_ = hex_ = upper_ = true;
else {
hex_ = (f == "x") || (f == "X");
upper_ = (f == "X");
}
return e;
}
auto format(cpp_int const& i, auto& ctx) {
auto f = hex_ ? std::ios::hex : std::ios::dec;
if (showbase_) f |= std::ios::showbase;
if (upper_) f |= std::ios::uppercase;
auto s = i.str(0, f);
return std::copy(s.begin(), s.end(), ctx.out());
}
};
int main() {{
cpp_int v("0x8FFFFFFFFFFFFFFFF");
fmt::print("{{}}: {}\n", v);
fmt::print("{{:}}: {:}\n", v);
fmt::print("{{:x}}: {:x}\n", v);
fmt::print("{{:#x}}: {:#x}\n", v);
fmt::print("{{:X}}: {:X}\n", v);
fmt::print("{{:#X}}: {:#X}\n", v);
}}
印刷
{}: 166020696663385964543
{:}: 166020696663385964543
{:x}: 8ffffffffffffffff
{:#x}: 0x8ffffffffffffffff
{:X}: 8FFFFFFFFFFFFFFFF
{:#X}: 0X8FFFFFFFFFFFFFFFF
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.