Skip to content

Instantly share code, notes, and snippets.

@mutac
Last active October 2, 2018 22:52
Show Gist options
  • Save mutac/9c5d11cb7a76832b77606f04d08fcf5c to your computer and use it in GitHub Desktop.
Save mutac/9c5d11cb7a76832b77606f04d08fcf5c to your computer and use it in GitHub Desktop.
Generate static array of c-compatible "anonymous" function with a numeric closure (c++14)
#include <stdio.h>
#include <utility>
typedef void (*FuncPtr)(const char* arg1, const char* arg2);
void Func(const char* arg1, const char* arg2, size_t arg3)
{
printf("%s %s %ld\n", arg1, arg2, arg3);
}
template <size_t Arg3>
struct BindFunc
{
static void Value(const char* arg1, const char* arg2)
{
Func(arg1, arg2, Arg3);
}
};
template <typename T, size_t Count, template <size_t> class Generator, typename I>
struct static_array_impl;
template <typename T, size_t Count, template <size_t> class Generator, size_t... I>
struct static_array_impl<T, Count, Generator, std::index_sequence<I...>>
{
static const T data[Count];
};
template <typename T, size_t Count, template <size_t> class Generator, size_t... I>
const T static_array_impl<T, Count, Generator, std::index_sequence<I...>>::data[Count] = { Generator<I>::Value... };
template <typename T, size_t Count, template <size_t> class Generator>
struct static_array : static_array_impl<T, Count, Generator, std::make_index_sequence<Count>>
{
};
static_array<FuncPtr, 10, BindFunc> table;
int main(int argc, const char* argv[])
{
for (const FuncPtr& func : table.data)
{
func("generated", "function");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment