c++ - Calling template function with conditionals -
given function type template :
template<typename typea, typename typeb, typename typec> void foo (typea a, typeb b, typec c) { ...; }
then hope call function approach shown follows:
int main (void) { int ta = 32; int tb = 64; int tc = 32; float *array_a; double *array_b; float *array_c; foo<(ta == 32 ? float : double), (tb == 32 ? float : double), (tc == 32 ? float : double)>(array_a, array_b, array_c); return 0; }
of course, code results in compile error...
however, wonder whether there convenient way check ta's, tb's, , tc's value , call function foo accordingly...
first of all, choosing type use instantiate template based on value of variable , conditional operator syntactically wrong. language doesn't allow type chosen method.
second, can let compiler deduce type. can use:
foo(array_a, array_b, array_c);
the compiler deduce typea
float*
, typeb
double*
, , typec
float*
.
using
foo<float, double, float>(array_a, array_b, array_c);
is not correct since types used instantiate template don't match argument types.
third, if want able derive type based on value, value has const
or constexpr
. can use:
template <int n> struct type_chooser { using type = double; }; template <> struct type_chooser<32> { using type = float; }; int main () { const int ta = 32; const int tb = 64; const int tc = 32; using typea = typename type_chooser<ta>::type; using typeb = typename type_chooser<tb>::type; using typec = typename type_chooser<tc>::type; foo<typea, typeb, typec>(10, 20, 30); return 0; }
Comments
Post a Comment