Proposal mpl::switch_case

My use case is a fast protocol decoder. I've described the protocol in mpl and generate the instructions I need to decode/encode/store packets. During decoding I have to be able to take a run time id and map it to the correct compile time generated code. Traditionally such code was written as a switch/case. The obvious solution is to use metaprogramatic recursion, for example mpl::for_each to check the id against each value. You would hope the compiler would inline all the recursion, detect the ifs on an id, and do general switch/case optimization. Unfortunately the code generated by gcc and it's not as good as I hoped. They actually generate a function for every ~6 levels of recursion and just do a bunch of if/equal/else. boost::variant has this same problem. They use BOOST_PP_REPEAT to generate an actual switch/case statement(visitation_impl.hpp). The compiler does a good job with the swich/case. It removes redundant cases and then optimizes using array lookups and binary searches depending on size. Good job! 1) Could we factor this logic out into a utility like mpl::switch_case? 2) What would the best interface look like? 3) What other bits of code could benefit from it? phoenix::switch_? Meta State Machine? Chris

2011/10/20 Hite, Christopher
My use case is a fast protocol decoder. I've described the protocol in mpl and generate the instructions I need to decode/encode/store packets. During decoding I have to be able to take a run time id and map it to the correct compile time generated code. Traditionally such code was written as a switch/case.
The obvious solution is to use metaprogramatic recursion, for example mpl::for_each to check the id against each value. You would hope the compiler would inline all the recursion, detect the ifs on an id, and do general switch/case optimization. Unfortunately the code generated by gcc and it's not as good as I hoped. They actually generate a function for every ~6 levels of recursion and just do a bunch of if/equal/else.
boost::variant has this same problem. They use BOOST_PP_REPEAT to generate an actual switch/case statement(visitation_impl.hpp). The compiler does a good job with the swich/case. It removes redundant cases and then optimizes using array lookups and binary searches depending on size. Good job!
1) Could we factor this logic out into a utility like mpl::switch_case?
2) What would the best interface look like?
3) What other bits of code could benefit from it? phoenix::switch_? Meta State Machine?
Is this what you want? http://dancinghacker.com/switch/
participants (2)
-
Hite, Christopher
-
TONGARI