C++ Utilities
Loading...
Searching...
No Matches
formatter.h
Go to the documentation of this file.
1#pragma once
2// SPDX-FileCopyrightText: 2025 Nessan Fitzmaurice <nzznfitz+gh@icloud.com>
3// SPDX-License-Identifier: MIT
4
9
10#include <concepts>
11#include <format>
12#include <cassert>
13
14namespace utilities {
15
17template<typename T>
18concept has_to_string = requires(const T& x) {
19 { x.to_string() } -> std::convertible_to<std::string>;
20};
21
22} // namespace utilities
23
35template<utilities::has_to_string T>
36struct std::formatter<T> {
37 template<class FormatContext>
38 auto format(const T& rhs, FormatContext& ctx) const
39 {
40 return std::format_to(ctx.out(), "{}", rhs.to_string());
41 }
42
43 constexpr auto parse(const std::format_parse_context& ctx)
44 {
45 // Throw an error for anything that is not default formatted.
46 // The `to_string()` method might handle various formatting options, but we cannot know that here.
47 auto it = ctx.begin();
48 assert(it == ctx.end() || *it == '}');
49 return it;
50 }
51};
#define assert(cond,...)
An assertion macro that checks a boolean condition cond. On failure, the assertion prints an error ...
Definition assert.h:99
A concept that matches any type that has an accessible std::string to_string() const method.
Definition formatter.h:18
The namespace for the utilities library.
Definition formatter.h:14