-
Notifications
You must be signed in to change notification settings - Fork 74
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[332] - Did you know that in C++ you can generate jump tables at comp…
…ile-time?
- Loading branch information
1 parent
44d66c7
commit 73ee938
Showing
3 changed files
with
112 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
<details open><summary>Info</summary><p> | ||
|
||
* **Did you know that in C++ you can generate jump tables at compile-time?** | ||
|
||
* https://en.wikipedia.org/wiki/Branch_table | ||
|
||
</p></details><details open><summary>Example</summary><p> | ||
|
||
```cpp | ||
template<auto N> constexpr auto foo() { return N; } | ||
|
||
constexpr std::array jump_table{ | ||
foo<0>, | ||
foo<1>, | ||
foo<2>, | ||
}; | ||
|
||
static_assert(0 == jump_table[0]()); | ||
static_assert(1 == jump_table[1]()); | ||
static_assert(2 == jump_table[2]()); | ||
``` | ||
> https://godbolt.org/z/x3xa9erGE | ||
</p></details><details open><summary>Puzzle</summary><p> | ||
* **Can you implemnt dispatch fn which generates jump table for given N?** | ||
```cpp | ||
template<auto N> constexpr auto foo() { return N; } | ||
template<auto N = 42> | ||
constexpr auto dispatch(auto n); // TODO | ||
static_assert(1 == dispatch(1)); | ||
static_assert(7 == dispatch(7)); | ||
static_assert(23 == dispatch(23)); | ||
``` | ||
|
||
> https://godbolt.org/z/4M9x1vjcG | ||
</p></details><details><summary>Solutions</summary><p> | ||
</p></details> |