Skip to content

Commit c624a03

Browse files
authored
Merge pull request #2 from engdoreis/develop
Add support to extend for custom types
2 parents 5d23cbb + 3b9a5c3 commit c624a03

File tree

5 files changed

+454
-322
lines changed

5 files changed

+454
-322
lines changed

README.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,41 @@ int main() {
4848
return 0;
4949
}
5050
```
51+
## How to extend the print for a custom type
52+
Custom types can be printed in two different ways.
53+
The first option and recommended in most cases is to implement the `concept Printable` for the type.
54+
```cpp
55+
struct Memory {
56+
size_t addr;
57+
size_t size;
58+
59+
// Printable concept
60+
template <typename T>
61+
inline void print(reisfmt::Fmt<T> &fmt) {
62+
fmt.print("Memory: addr: {:#x}, size: {}", addr, size);
63+
}
64+
};
65+
```
66+
The second option is more verbose and may be needed in some cases where the type is defined by an external library. Here we specialize the struct `Formatter` for the desired type.
67+
```cpp
68+
struct Memory {
69+
size_t addr;
70+
size_t size;
71+
};
72+
73+
namespace reisfmt {
74+
template <typename T>
75+
struct Formatter<T, Memory> {
76+
static inline void print(Fmt<T> &fmt, Memory &obj) {
77+
fmt.print("Memory: addr: {:#x}, size: {}", obj.addr, obj.size);
78+
}
79+
};
80+
}
81+
```
82+
Now you can print the `struct Memory` using the `fmt` library.
83+
```cpp
84+
fmt_.println("{}", Memory{0x1000'0000, 1024 * 256});
85+
```
5186
5287
## Formating specification
5388
This library follows the libc++ format specification defined [here](https://en.cppreference.com/w/cpp/utility/format/spec).

0 commit comments

Comments
 (0)