-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy path310.md
85 lines (64 loc) · 2 KB
/
310.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<details open><summary>Info</summary><p>
* **Did you know that C+23 permitts static constexpr variables in constexpr functions?**
* https://wg21.link/P2647
</p></details><details open><summary>Example</summary><p>
```cpp
constexpr auto foo() {
static constexpr auto value = 42; // error in C++20, okay in C++23
return value;
}
```
> https://godbolt.org/z/6zK6vj91z
</p></details><details open><summary>Puzzle</summary><p>
> **Can you implement `to_string_view` which converts in-place given characters to string_view?**
```cpp
template<char... Cs>
[[nodiscard]] constexpr auto to_string_view(); // TODO
static_assert(std::string_view{""} == to_string_view<>());
static_assert(std::string_view{"42"} == to_string_view<'4', '2'>());
static_assert(std::string_view{"foo"} == to_string_view<'f', 'o', 'o'>());
static_assert(std::string_view{"bar"} == to_string_view<'b', 'a', 'r'>());
```
> https://godbolt.org/z/4fbYGGxco
</p></details><details><summary>Solutions</summary><p>
```cpp
template<char... Cs>
[[nodiscard]] constexpr auto to_string_view(){
static constexpr char p[sizeof...(Cs)] = {Cs...};
return std::string_view(p, sizeof...(Cs));
}
```
> https://godbolt.org/z/r31M7hhno
```cpp
template<char... Cs>
[[nodiscard]] constexpr auto to_string_view(){
static constexpr std::array<char, sizeof...(Cs)> chars{Cs...};
return std::string_view{chars};
}
template<>
[[nodiscard]] constexpr auto to_string_view<>(){
return std::string_view{};
}
```
> https://godbolt.org/z/eTWasjTTr
```cpp
[[nodiscard]] constexpr auto to_string_view()
{
constexpr static std::size_t N = sizeof...(Cs);
if constexpr (N >0)
{
constexpr static std::array<char,N> chars{Cs...};
return std::string_view(chars.data(),N);
} else
return std::string_view("");
}
```
> https://godbolt.org/z/9MMKv98dE
```cpp
template<char... Cs>
[[nodiscard]] constexpr auto to_string_view() {
static constexpr char cs[]{Cs..., 0};
return std::string_view{cs};
}
```
> https://godbolt.org/z/PPdxETv76