Skip to content

Instantly share code, notes, and snippets.

@talybin
Last active August 25, 2021 21:18
Show Gist options
  • Save talybin/931ae8081e94d37a037f6ca089291031 to your computer and use it in GitHub Desktop.
Save talybin/931ae8081e94d37a037f6ca089291031 to your computer and use it in GitHub Desktop.
Yet another way to convert run-time integer to constant.
#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';
}
@talybin
Copy link
Author

talybin commented Aug 21, 2021

generated: 12
found: 0
generated: 9
const value: 9
found: 1

@talybin
Copy link
Author

talybin commented Aug 25, 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