Skip to content

Instantly share code, notes, and snippets.

@gatchamix
Last active May 12, 2021 14:52
Show Gist options
  • Save gatchamix/69bf3560f4fdbda52b3025fe27341e5a to your computer and use it in GitHub Desktop.
Save gatchamix/69bf3560f4fdbda52b3025fe27341e5a to your computer and use it in GitHub Desktop.
constexpr map
#include <utility>
#include <array>
template <auto...>
struct value_list
{};
template <class T, auto... Keys>
struct map_
{
using data_type = T;
static auto constexpr N = sizeof...(Keys);
constexpr map_(value_list<Keys...>, std::array<T, N> arr)
: arr_{ arr }
{}
private:
template <class Key, std::size_t... Is>
auto constexpr at_impl(Key key, std::index_sequence<Is...>) const
{ return ((key == Keys ? Is + 1 : 0) + ...) - 1; }
public:
template <class Key>
auto constexpr at(Key const key) const
{ return arr_.at(at_impl(key, std::make_index_sequence<N>{})); }
template <class Key>
auto constexpr operator[](Key const i) const
{ return at(i); }
private:
std::array<T, N> arr_;
};
int main()
{
auto constexpr seq = value_list<'a', 1>{};
auto constexpr arr = std::array<int(*)(), 2>
{ []() { return 1; }, []() { return 2; } };
auto constexpr map = map_{ seq, arr };
auto constexpr fun = map['a'];
auto constexpr val = fun();
return val;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment