vendredi 12 août 2016

Idiom for simulating run-time numeric template parameters?

Suppose we have

template <unsigned N> foo() { /* ... */ }

defined. Now, I want to implement

do_foo(unsigned n);

which calls the corresponding variant of foo(). This is not merely a synthetic example - this does actually happen in real life (of course, not necessarily with void-to-void functions and just one template parameter, but I'm simplfying. Of course, in C++, we can't have the following:

do_foo(unsigned n) { foo<n>(); }

and what I do right now is

do_foo(unsigned n) { 
    switch(n) {    
    case n_1: foo<n_1>(); break;
    case n_2: foo<n_2>(); break;
    /* ... */
    case n_k: foo<n_k>(); break;
    }
}

when I know n is effectively limited in range to n_1,...,n_k. But this is unseemly, and much more so when the call is longer and I need to duplicate a long sequence of template and regular parameters many times.

I was about to start working on a macro to produce these switch statements, when I got to thinking maybe someone has already worked on this in some library and could share what they did. If not, perhaps it's still feasible to have some kind of C++ construct which takes an arbitrary function, with any sequence of template and non-template parameters including some numeric template parameter, and a sequence of values in some form, to produce a wrapper which can take that template parameter as an additional run-time parameter instead, e.g.

auto& transformed_foo = magic<decltype(foo)>(foo)::transformed;





Aucun commentaire:

Enregistrer un commentaire