Optimisation design advice - metaprogramming/closures

There are various simple ways to do this using higher-order functions, but please keep in mind that asking for a fully optimized, zero-overhead, and convenient solution without providing an MWE is somewhat unrealistic.