Wie deklariere ich ein STD :: Formatierer für einen benutzerdefinierten Typ?
Posted: 05 Apr 2025, 21:07
Stellen Sie sich einen sehr einfachen Punkt vor Klasse:
Wenn ich jetzt versuche, einen Punkt zu formatieren, funktioniert es gut:
Code: Select all
class Point final
{
private:
std::int32_t m_x;
std::int32_t m_y;
public:
explicit Point(const std::int32_t x = 0, const std::int32_t y = 0)
: m_x(x), m_y(y)
{}
// Are these necessary?
// Point(const Point& other) = default;
// Point(Point&& other) = default;
// Point& operator=(const Point& other) = default;
// Point& operator=(Point&& other) = default;
friend struct std::formatter
;
};
template
struct std::formatter
: std::formatter
{
std::format_context::iterator
format(const Point& p, std::format_context& ctx)
const
{
const std::string s = std::format("x:{}, y:{}", p.m_x, p.m_y);
const std::format_context::iterator x = formatter::format(s, ctx);
return x;
}
};
Code: Select all
class Dummy final:
{
static void
print()
{
Point p{2, 3};
const std::string s = std::format("Point: {}", p);
std::cout