Skip to content

Commit 994a105

Browse files
committed
range_formatter のコード例を追加
set_separator と set_brackets を使うと、元の例と同じものをより短く書けます。 元の例は underlying の使い方の参考になるので、元の例を残したまま新しい例を追加しました。
1 parent 5c792ff commit 994a105

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

reference/format/range_formatter.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,57 @@ int main()
136136
aa:bb:cc:dd:ee:ff
137137
```
138138

139+
140+
### オリジナル書式を定義する例(`set_separator``set_brackets`を使う場合)
141+
```cpp example
142+
#include <iostream>
143+
#include <format>
144+
#include <vector>
145+
146+
template <class T>
147+
struct MyVector : std::vector<T> {
148+
using std::vector<T>::vector;
149+
};
150+
151+
template <class T>
152+
constexpr std::range_format std::format_kind<MyVector<T>> = std::range_format::sequence;
153+
154+
template <class T>
155+
class std::formatter<MyVector<T>> : public std::range_formatter<T> {
156+
using base_type = std::range_formatter<T>;
157+
public:
158+
constexpr auto parse(std::format_parse_context& pctx) {
159+
auto it = pctx.begin();
160+
if (*it == 'c') {
161+
this->set_separator(":"); // 区切り文字を「:」に設定
162+
this->set_brackets("", ""); // 囲み文字を空文字列に設定
163+
++it;
164+
}
165+
pctx.advance_to(it);
166+
return base_type::parse(pctx);
167+
}
168+
};
169+
170+
#include <cstdint>
171+
172+
int main()
173+
{
174+
MyVector<std::uint8_t> v = {0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff};
175+
std::cout << std::format("{:c:02x}", v) << std::endl;
176+
}
177+
```
178+
* std::format_parse_context[link basic_format_parse_context.md]
179+
* pctx.begin()[link basic_format_parse_context/begin.md]
180+
* pctx.advance_to[link basic_format_parse_context/advance_to.md]
181+
* std::format[link format.md]
182+
183+
184+
#### 出力
185+
```
186+
aa:bb:cc:dd:ee:ff
187+
```
188+
189+
139190
## バージョン
140191
### 言語
141192
- C++23

0 commit comments

Comments
 (0)