Is it possible to decide in run-time which template function to call?
Something like:
template<int I>
struct A {
static void foo() {/*...*/}
};
void bar(int i) {
A<i>::f(); // <-- ???
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A typical ‘trick’ to bridge compile time and runtime when dealing with templates is visiting a variant type. That’s what the Generic Image Library (available as Boost.GIL or standalone) does for instance. It typically takes the form of:
where
visitoris a polymorphic functor that simply forwards to the template:This has the nice design that the list of types that the template will/can be instantiated with (here, the
variant_typetype synonym) is not coupled to the rest of the code. Metafunctions likeboost::make_variant_overalso allows computations over the list of types to use.Since this technique is not available to non-type parameters, you need to ‘unroll’ the visitation by hand, which unfortunately means the code is not as readable/maintainable.
The usual way to deal with the repetition in the above switch is to (ab)use the preprocessor. An (untested) example using Boost.Preprocessor:
Better find good, self-documenting names for
LIMIT(wouldn’t hurt forPASTEeither), and limit the above code-generation to just one site.Building from David’s solution and your comments:
then to call
bar:bar(i, typename build_indices<N>::type())whereNwould be your constant-time constant,sizeof...(something). You can add a layer to hide the ‘ugliness’ of that call:which is called as
bar<N>(i).