c++ - “Overload” function template based on function object operator() signature in C++98 -
i want make template function takes function , vector , uses function map vector vector returned function template.
if function taken argument free function, may have 1 of 2 signatures.
// t parameter of function template t sig1(const t x); t sig2(const t x, const std::vector<t>& v);
it may function object in operator()
behave free functions. use of function template of 4 possibilities should transparent.
std::vector<int> v; // ... fill v somehow ... // foo either free function or function object instance const std::vector<int> = map_vec(foo, v);
i asked how c++11 , got great answer 0x499602d2.
"overload" function template based on function object operator() signature
0x499602d2's answer makes use of fact these 2 distinct template signatures in c++11:
template<typename f, typename t> auto map_vec(f&& fnc, const std::vector<t>& source) -> decltype(void(fnc(std::declval<t>())), std::vector<t>{}); template<typename f, typename t> auto map_vec(f&& fnc, const std::vector<t>& source) -> decltype(void(fnc(std::declval<t>(), source)), std::vector<t>{});
i know how solve in c++98.
here effort far. have sfinae struct can determine if function objects takes 2 args. don't know how working both function objects , free functions. either need change sfinae struct work on both function objects , free functions or need use overloading route function objects , free functions separately.
here's approach:
template <std::size_t, typename t = void> struct ignore_value {typedef t type;}; template <typename t> t& declval(); template<typename f, typename t> typename ignore_value<sizeof(declval<f>()(declval<t const>())), std::vector<t> >::type map_vec(f fnc, const std::vector<t>& source); template<typename f, typename t> typename ignore_value<sizeof(declval<f>() (declval<t const>(), declval<const std::vector<t> >())), std::vector<t> >::type map_vec(f fnc, const std::vector<t>& source);
it works same demo 0x499602d2 used, both gcc , clang in c++98 mode.
Comments
Post a Comment