On Wed, Jul 28, 2010 at 4:37 PM, Hite, Christopher <christopher.h...@partner.commerzbank.com> wrote: > > > > I'm writing a decoder using a meta programming techniques alla > boost::mpl and I'd like to know if I'm asking too much of the compiler. > > Basically I've got lots of packet types with different ids. The > classical way to write these would be a switch case > > int id; > switch(id){ > case Id1: decode1() break; > case Id2: decode2() break; > ... > } > > I'm tring to use the template compiler to generate equivalent code. I > have a mpl::list of packet descriptions like this: > struct Packet1{ > static const int id=1; > void decode(); > }; > > I then use boost::mpl::fold to generate a decode function which might > look sort of like this: > > void decode1(int id){ > if(id==1) > Packet1::decode(); > else > decode2(id); > } > > What I'm hoping is that the compiler is smart enough > * to inline all decode*() calls into one function > * to notice I compare id to N constants and use switch case optimization > (binary search or lookup table) > > Am I asking too much? > > Do I have to watch for any pitfalls that willl break the optimization, > like making id a member of a class or leaving out the 'else' ? > > > I could write more complicated meta-code which sorts by id and does a > runtime binary search, that would probably prevent the optimizer from > doing anything smarter.
Generally without knowing the compiler version you are using it is hard to tell. The same is true without a complete compilable testcase. You can use the flatten attribute to tell the compiler to inline all calls in a given function, like void __attribute__((flatten)) foo(void) { ... decode1(); ... } and it will inline decode1() (and recursively all its callees). Richard. > Chris Hite > >