Skip to content

Instantly share code, notes, and snippets.

@jonvaldes
Created March 7, 2013 13:08
Show Gist options
  • Save jonvaldes/5107929 to your computer and use it in GitHub Desktop.
Save jonvaldes/5107929 to your computer and use it in GitHub Desktop.
Coworker asked if I knew how to do a "for" with C macros, to avoid manually instantiating lots of helper functions. Here's a template metaprogramming-based solution, wich creates an array-like struct that contains 500 pointers to function you can then call. Woot! Note that the maximum T allowed by clang is 512, while gcc sets the maximum at 500 …
#include <cstdio>
template <int T> void func(){printf("Number %d\n", T);}
typedef void (*functype)();
template <int T> struct funcs
{
funcs<T-1> rest ;
functype f ;
funcs() : f( func<T> ) {}
functype operator[](int i) { return reinterpret_cast<functype*>(this)[i] ; }
};
template <> struct funcs <0>
{
functype f ;
funcs() : f( func<0> ) {}
};
funcs<500> funcInstances ;
int main()
{
for( int i = 0 ; i < 500; ++i )
funcInstances[i]();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment