formatters for std::format and std::print

This commit is contained in:
Hartmut Seichter 2024-07-22 22:40:38 +02:00
parent 980ede013f
commit 6a0c5c178d

View file

@ -0,0 +1,69 @@
/*
* Copyright (c) 1999-2021 Hartmut Seichter
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#ifndef PW_CORE_FORMATTER_HPP
#define PW_CORE_FORMATTER_HPP
#include <pw/core/globals.hpp>
#include <pw/core/matrix.hpp>
#include <pw/core/vector.hpp>
#include <format>
#include <numeric>
#include <string>
template <typename Scalar, std::size_t N>
struct std::formatter<pw::vector<Scalar, N>> {
constexpr auto parse(std::format_parse_context& ctx) { return ctx.begin(); }
constexpr auto format(const pw::vector<Scalar, N>& v,
std::format_context& ctx) const noexcept {
return std::format_to(
ctx.out(), "{}",
std::accumulate(std::next(std::begin(v)), std::end(v),
std::to_string(v[0]),
[](const auto& prev, const auto& e) {
return prev + " " + std::to_string(e);
}));
}
};
template <typename Scalar, std::size_t Rows, std::size_t Cols>
struct std::formatter<pw::matrix<Scalar, Rows, Cols>> {
constexpr auto parse(std::format_parse_context& ctx) { return ctx.begin(); }
constexpr auto format(const pw::matrix<Scalar, Rows, Cols>& m,
std::format_context& ctx) const noexcept {
return std::format_to(
ctx.out(), "{}",
std::accumulate(std::next(std::begin(m)), std::end(m),
std::format("{}", m[0]),
[](const auto& prev, const auto& e) {
return prev + "\n" + std::format("{}", e);
}));
}
};
#endif