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]...);     } }; 

live example

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:

live demo


Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -