-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy path346.md
60 lines (41 loc) · 1.68 KB
/
346.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<details open><summary>Info</summary><p>
* **Did you know that C++26 added testing for success or failure of <charconv> functions?**
* https://wg21.link/P2497
</p></details><details open><summary>Example</summary><p>
```cpp
constexpr std::to_chars_result result{{}};
static_assert(result);
```
> https://godbolt.org/z/q16djPn3P
</p></details><details open><summary>Puzzle</summary><p>
* **Can you implement `format` fn which optionally converts given value to chars?**
```cpp
template <auto N>
constexpr auto format(const auto value) -> std::optional<std::array<char, N>>; // TODO
constexpr auto fmt_0 = format<1>(0);
static_assert(fmt_0 and std::string_view{fmt_0->cbegin(), fmt_0->cend()} == std::string_view{"0"});
constexpr auto fmt_42 = format<2>(42);
static_assert(fmt_42 and std::string_view{fmt_42->cbegin(), fmt_42->cend()} == std::string_view{"42"});
```
> https://godbolt.org/z/rf7rWc3ee
</p></details>
</p></details><details><summary>Solutions</summary><p>
```cpp
template <auto N>
constexpr auto format(const auto value) -> std::optional<std::array<char, N>> {
std::array<char, N> buffer;
return std::to_chars(buffer.begin(), buffer.end(), value)
? std::optional(buffer)
: std::nullopt;
};
constexpr auto fmt_0 = format<1>(0);
static_assert(fmt_0 and std::string_view{fmt_0->cbegin(), fmt_0->cend()} ==
std::string_view{"0"});
constexpr auto fmt_42 = format<2>(42);
static_assert(fmt_42 and std::string_view{fmt_42->cbegin(), fmt_42->cend()} ==
std::string_view{"42"});
constexpr auto fmt_error = format<1>(42);
static_assert(!fmt_error);
```
> https://godbolt.org/z/c8vWbGKWf
</p></details>