Last active
August 25, 2021 21:18
-
-
Save talybin/931ae8081e94d37a037f6ca089291031 to your computer and use it in GitHub Desktop.
Yet another way to convert run-time integer to constant.
This file contains hidden or 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
#include <iostream> | |
#include <ctime> | |
#include <utility> | |
template <class T, class F, T... I> | |
bool to_const(T value, F&& fn, std::integer_sequence<T, I...>) { | |
return ( | |
(value == I && (fn(std::integral_constant<T, I>{}), true)) | |
|| ... // or continue | |
); | |
} | |
template <std::size_t Size, class T, class F> | |
bool to_const(T value, F&& fn) { | |
return to_const(value, fn, std::make_integer_sequence<T, Size>{}); | |
} | |
template <int I> | |
void print() { | |
std::cout << "const value: " << I << '\n'; | |
} | |
int main() | |
{ | |
int id = time(0) % 20; | |
std::cout << "generated: " << id << '\n'; | |
// id in range 0..19, to_const search in range 0..9 | |
bool found = to_const<10>(id, [](auto I) | |
{ | |
print<I>(); | |
}); | |
std::cout << "found: " << found << '\n'; | |
} |
Author
talybin
commented
Aug 21, 2021
GCC 11 is able to optimize away comparison in to_const()
completely, and build a jump table using input index to select right method.
jmp [QWORD PTR .L4[0+rax*8]]
Where rax
is id
and .L4
is jump table.
See result here
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment