Skip to content

Instantly share code, notes, and snippets.

@ldionne
Created May 13, 2015 02:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ldionne/0d948811db18a637ddcb to your computer and use it in GitHub Desktop.
Save ldionne/0d948811db18a637ddcb to your computer and use it in GitHub Desktop.
implementation of a function pointer table
// Copyright Louis Dionne 2015
// Distributed under the Boost Software License, Version 1.0.
#include <boost/hana.hpp>
#include <array>
using namespace boost::hana;
template <typename T>
void visit(T t) { }
template <typename ...T>
std::array<void(*)(void*), sizeof...(T)> function_table = {{
[](void* v) -> decltype(auto) {
return visit<T>(*static_cast<T*>(v));
}...
}};
int main() {
auto table = function_table<int, float, char>;
auto visit_as_int = table[0];
auto visit_as_float = table[1];
auto visit_as_char = table[2];
#if 0 // just ignore this
auto function_map = [](auto ...types) {
return to<Map>(transform(make_tuple(types...), [](auto t) {
using T = typename decltype(t)::type;
return make_pair(type<T>, [](void* v) -> decltype(auto) {
return visit<T>(*static_cast<T*>(v));
});
}));
};
auto functions = function_map(type<int>, type<float>, type<char>);
void* v = nullptr;
functions[type<int>](v);
#endif
}
@ned14
Copy link

ned14 commented May 13, 2015

Get the visitor to do something e.g. print something unique.

Print sizeof(function_table) to prove to people it's optimally stored (I explain why below).

My very old visitor metaprogram is at https://github.com/ned14/tnfox/blob/master/include/FXGenericTools.h#L2198 with the implementation at https://github.com/ned14/tnfox/blob/master/include/FXGenericTools.h#L2171. In those days C array sizes could not be calculated at compile time on many compilers, the traditional workaround was recursive inheritance but that triggers a "feature" in MSVC where it pads between array items, and that had a big negative effect on performance. So I was stuck with fixed size arrays. Still, it shows a visitor pattern in action.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment