c++ - choose correct template specialization at run-time -
i have
template <int i> struct { static void f (); }; with specializations done @ different places in code. how can call correct a<i>::f i known @ runtime?
void f (int i) { a<i>::f (); } // won't compile i don't want list possible values of i in big switch.
edit:
i thought of like
#include <iostream> template <int i> struct { static void f (); }; struct regf { typedef void (*f)(); enum { arrsize = 10 }; static f v[arrsize]; template < int > static int apply (f f) { static_assert (i < arrsize, ""); v[i] = a<i>::f; return 0; } }; regf::f regf::v[arrsize]; template <int i> struct reg { static int dummy; }; template <int i> int reg<i>::dummy = regf::apply<i> (); void f (int i) { return regf::v[i] (); } #define add(i) \ template <> struct a<i> : reg<i> { \ static void f () { std::cout << << "\n"; } \ }; add(1) add(3) add(5) add(7) int main () { f (3); f (5); } but crashes (did miss force instantiation?), , don't dummy not static const (and uses memory) , of course arrsize bigger necessary.
actual problem: have function generate (int i) calls a<i>::generate () generate instance of class a<i> i given @ run-time. design (classes a<i>) given, inherit base class , more specializations of added @ time anywhere in code, don't want force change generate (i) manually forgotten easily.
i not sure best solution can get, there might better designs, @ rate can use metaprogramming trigger instantiation , registry of functions:
// in single cpp file namespace { template <unsigned int n> int register_a() { // return artificially added register_a<n-1>(); // initialize array 0 n-1 regf::v[n] = &a<n>::f; // , n return n; } template <> int register_a<0>() { regf::v[0] = &a<0>::f; // recursion stop condition return 0; } const int ignored = register_a<regf::arrsize>(); // call } that code instantiate functions , register pointers static member functions. fake return type required able force execution of function in static context (by means of using function initialize static value).
this quite prone static initialization fiasco. while regf::v ok, code depends on regf::v containing appropriate pointers during static initialization bound fail. can improve usual techniques...
from bits , pieces have posted, guess trying use abstract factory automated registration each 1 of concrete factories. there better ways of approaching problem, think answer solves question (i unsure on whether solve problem).
Comments
Post a Comment