Я пытаюсь указать форматировщик для печати mdspan ранга 2 в виде матрицы, что весьма полезно. Мне бы хотелось, чтобы хотя бы форматирование элементов работало, например. std::println("{::.2e}", матрица) напечатает некоторую двойную матрицу в формате .2e для двойных значений. Трудность в том, что это нужно делать во время компиляции, я не понимаю, как это вообще делается: "{:" + std::string{spec} + "}" здесь не время компиляции, поэтому терпит неудачу. Было бы полезно увидеть, как это делается, или получить общие советы по реализации форматирования.
#include
#include
#include
template
requires (Extents::rank() == 2)
struct std::formatter {
std::string_view spec;
constexpr auto parse(format_parse_context& ctx) {
auto it = ctx.begin();
auto end = ctx.end();
spec = std::string_view{it, end};
return end;
}
auto format(const std::mdspan& md, format_context& ctx) const {
auto out = ctx.out();
*out++ = '[';
for (size_t i = 0; i < md.extent(0); ++i) {
if (i > 0) {
*out++ = '\n';
*out++ = ' ';
}
*out++ = '[';
for (size_t j = 0; j < md.extent(1); ++j) {
if (j > 0)
*out++ = ' ';
if (spec.empty())
out = std::format_to(out, "{}", md[i, j]);
else
out = std::format_to(out, "{:" + std::string{spec} + "}", md[i, j]);
}
*out++ = ']';
}
*out++ = ']';
return out;
}
};
int main() {
std::println("{::.2e}", std::mdspan((double []) {1.1111, 2, 3, 4}, 2, 2));
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... -as-matrix