Working around the static type property of C++ -
consider piece of code
template<typename t> void call_me(const t& arg) { } template<int i> struct custom_type { }; void foo(int i) { switch (i) { case 0: call_me( custom_type<0>() ); break; case 1: call_me( custom_type<1>() ); break; case 2: call_me( custom_type<2>() ); break; default: break; } }
the switch statement incomplete in sense of meant do, i.e. work integers not few explicitly mentioned above. c++ won't allow statement custom_type<i>
because i
not constant expression. (..and can't change argument function foo
constant expression). not use external code generator generates huge switch statement , feeds source code..
is there way in c++/11/14/17 allow writing function call call_me
in elegant way, or answer just, 'no, c++ statically typed.'?
something should work, addition of special case call_me_t<0>
template <int n> struct call_me_t { static void exec(int i) { if (i < n) call_me_t<n-1>::exec(i) ; else if (i == n) call_me(custom_type<n>()) ; } } ; template<> struct call_me_t<0> { static void exec(int i) { call_me(custom_type<0>()) ; } }; void foo(int i) { call_me_t<10>::exec(i) ; // 10 maximum value in switch }
Comments
Post a Comment