Skip to content

Instantly share code, notes, and snippets.

@n0phx
Created May 17, 2018 06:57
Show Gist options
  • Save n0phx/29d22e0d41759b647b5acd5335cda9c4 to your computer and use it in GitHub Desktop.
Save n0phx/29d22e0d41759b647b5acd5335cda9c4 to your computer and use it in GitHub Desktop.
Elegant jump table abstraction
struct not_found
{
};
template <typename TKey, typename TValue, TKey...>
struct JumpTable;
template <typename TKey, typename TValue>
struct JumpTable<TKey, TValue>
{
TValue& operator[]([[maybe_unused]] TKey needed)
{
throw not_found{};
}
};
template <typename TKey, typename TValue, TKey key, TKey... rest>
struct JumpTable<TKey, TValue, key, rest...> : JumpTable<TKey, TValue, rest...>
{
TValue value;
using super = JumpTable<TKey, TValue, rest...>;
TValue& operator[](TKey k)
{
return key == k ? value : super::operator[](k);
}
};
int fn1(int x)
{
return x + 1;
}
int fn2(int x)
{
return x + 2;
}
int fn3(int x)
{
return x + 3;
}
int main()
{
JumpTable<DispatchId,
FuncType,
DispatchId::Id1,
DispatchId::Id2,
DispatchId::Id3> jt;
jt[DispatchId::Id1] = fn1;
jt[DispatchId::Id2] = fn2;
jt[DispatchId::Id3] = fn3;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment