c++ - How to fix this template: -
template <typename in,typename out,bool isvector> out foo(in x){ if (isvector){ return x[0]; } else { return x; } }
after asking this question wrongly assumed, above code compile e.g.
foo<double,double,false>;
as as
foo<std::vector<double>,double,true>;
however, if 1 of if-branches never gets executed, checked correctness , above not compile. how can fix it?
the code above simplified, dont know how fix it, function templates cannot have partial specialization...
you can "extract" template parameters want specialize on, make them template parameters of structure, , write function remaining template parameters static member function:
template<bool isvector = true> struct bar { template<typename in> static auto foo(in input) { return input[0]; } }; template<> struct bar<false> { template<typename in> static auto foo(in input) { return input; } };
obviously results in change @ call site, can "catch" using free function calling appropriate function:
template<typename in, bool isvector> auto real_foo(in input) { return bar<isvector>::foo(input); }
the structures (bar
) put inside "helper" namespace.
another possibility use tags , overload resolution:
template<typename in> auto foo(in input, std::true_type) { return input[0]; } template<typename in> auto foo(in input, std::false_type) { return input; } template<bool isvector, typename in> auto foo(in input) { using tag = typename conditional<isvector, true_type, false_type>::type; return foo(input, tag{}); }
this uses std::conditional
std::true_type
, std::false_type
different types allow overload resolution find appropriate foo
function.
Comments
Post a Comment