Skip to content

Commit

Permalink
373 - Did you know that C++23 added constexpr bitset?
Browse files Browse the repository at this point in the history
  • Loading branch information
kris-jusiak committed May 19, 2024
1 parent adba672 commit 123c8a9
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@

> C++23
* [Did you know that C++23 added constexpr `bitset`?](https://github.com/tip-of-the-week/cpp/blob/master/tips/373.md)
* [Did you know that C++23 added Explicit lifetime management (1/N)?](https://github.com/tip-of-the-week/cpp/blob/master/tips/368.md)
* [Did you know that C++23 added spanstream - A strstream replacement using span<charT> as buffer?](https://github.com/tip-of-the-week/cpp/blob/master/tips/360.md)
* [Did you know that C++23 added standard support for `flat_map`?](https://github.com/tip-of-the-week/cpp/blob/master/tips/357.md)
Expand Down
54 changes: 54 additions & 0 deletions tips/373.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<details open><summary>Info</summary><p>

* **Did you know that C++23 added constexpr `bitset`?**

* https://wg21.link/P2417

</p></details><details open><summary>Example</summary><p>

```cpp
#include <bitset>
constexpr std::bitset<8> bs{0b00000001};
static_assert(bs.test(0));
static_assert(not bs.test(1));
```
> https://godbolt.org/z/W4v1Kqcfv
</p></details><details open><summary>Puzzle</summary><p>
* **Can you implement bitset `reverse`?**
```cpp
template<auto Size>
constexpr auto reverse(std::bitset<Size> bs); // TODO
static_assert(0b10000000 == reverse(std::bitset<8>{0b00000001}));
static_assert(0b10000001 == reverse(std::bitset<8>{0b10000001}));
static_assert(0b11100001 == reverse(std::bitset<8>{0b10000111}));
```

> https://godbolt.org/z/d75sW5E9x
</p></details>

</p></details><details><summary>Solutions</summary><p>

```cpp
template<auto Size>
constexpr auto reverse(std::bitset<Size> bs) {
std::bitset<Size> r{};
for (auto i = 0; i < bs.size(); ++i) {
r[r.size()-i-1] = bs[i];
}
return r;
}

static_assert(0b10000000 == reverse(std::bitset<8>{0b00000001}));
static_assert(0b10000001 == reverse(std::bitset<8>{0b10000001}));
static_assert(0b11100001 == reverse(std::bitset<8>{0b10000111}));
```
> https://godbolt.org/z/8h9PGP5o6
</p></details>

0 comments on commit 123c8a9

Please sign in to comment.