-1

Using the following class, I would like to be able to create an instance of a specified Foo() to store and call a function, but how can I transmit the necessary arguments to a function call ?

template<class R, class... Args> struct Foo {
    std::function<R(Args...)> func;

    Foo(const std::function<R(Args...)> &funcIn) : func(funcIn) {}

    R call(Args...) {
        return func(/* ? */);
    }
};

E.g:

int main() {
    typedef typename Foo<int(int)> Bar;
    Bar x([](int y, int z){return y + z + 2;});
    std::cout << x.call(12, 7);
    return 0;
}
273K
  • 29,503
  • 10
  • 41
  • 64
Benjamin Barrois
  • 2,566
  • 13
  • 30

2 Answers2

1

It is simple. Just add name of arguments.

R call(Args... args) {
    return func(args...);
}
273K
  • 29,503
  • 10
  • 41
  • 64
0

To make it simple

R call (Args... as) {
    return func(as...);
}

This should work well if the Args... types are int, long, float and other simple types without support for move syntax.

If you want add perfect forwarding, something as

template <typename ... As>
R call (As && ... as) {
    return func(std::forward<As>(as)...);
}

--- EDIT ---

If I understand correctly (?) according Smit Ycyken this code doesn't even compile.

There are some errors in the OP original code (the class Foo should be a struct or make something public; the typedef in main() is wrong) but the following corrected code compile with my g++ and my clang++

#include <iostream>
#include <functional>

template<class R, class... Args> struct Foo {
    std::function<R(Args...)> func;

    Foo(const std::function<R(Args...)> &funcIn) : func(funcIn) {}

    R call (Args... as) {
       return func(as...);
    }
};

int main ()
 {
   typedef Foo<int, int, int> Bar;
   Bar x([](int y, int z){return y + z + 2;});
   std::cout << x.call(12, 7);
   return 0;
 }
max66
  • 65,235
  • 10
  • 71
  • 111