c++ - Passing a variadic function as argument -
consider working code:
#include <iostream> #include <utility> #include <array> template <typename... args> void foo (args&&... args) { const auto v = {args...}; (auto x : v) std::cout << x << ' '; std::cout << '\n'; } template <typename> struct foo; template <std::size_t... is> struct foo<std::index_sequence<is...>> { template <typename container> static void execute (const container& v) { foo(v[is]...); } }; template <std::size_t n> void fooarray (const std::array<int, n>& a) { foo<std::make_index_sequence<n>>::execute(a); } int main() { fooarray<6>({0,1,2,3,4,5}); // 0 1 2 3 4 5 }
i want generalize foo
struct so:
#include <iostream> #include <utility> #include <array> template <typename... args> void foo (args&&... args) { const auto v = {args...}; (auto x : v) std::cout << x << ' '; std::cout << '\n'; } template <typename> struct foo; template <std::size_t... is> struct foo<std::index_sequence<is...>> { template <typename container, typename f> // *** modified static void execute (const container& v, f f) { f(v[is]...); } }; template <std::size_t n> void fooarray (const std::array<int, n>& a) { foo<std::make_index_sequence<n>>::execute(a, foo); } int main() { fooarray<6>({0,1,2,3,4,5}); }
but compile error (from gcc 4.9.2) f cannot deduced. how achieve this?
foo
family of overloads, , foo
ambiguous.
(even foo<int, int>
is, may have additional type too).
you may force expected type function follow:
template <std::size_t... is> struct foo<std::index_sequence<is...>> { template <typename container> static void execute (const container& v, void (*f)(decltype(v[is])&...)) { f(v[is]...); } };
an alternative wrap function foo
class:
class foocaller { public: template <typename... args> void operator () (args&&... args) const { const auto v = {args...}; (auto x : v) std::cout << x << ' '; std::cout << '\n'; } };
and keep implementation:
Comments
Post a Comment