0

EDIT -- Found an answer here.

In C++, I am trying to make a functor that I can hand specific variables to use as its function's arguments when I construct it. It uses a variadic template to pass in the argument types and return type of the function pointer. Then it uses a variadic constructor to get the argument values it should use. In code:

template <typename Return, typename... Args>
class Functor {
public:
    Functor(Return(*func)(Args...), Args... args) :
            function(func), arguments(args) {}

    // This overload to make the class "quack like a function"
    Return operator()() { return (*function)(arguments); }

private:
    Return(*function)(Args...);
    Args... arguments;     // <-- Right here is the problem. I don't
                           //     believe this is possible.

}

And how it would be used:

#include <iostream>

float add(int x, int y) { return x + y; }

int main() {
    // Template arguments: returns float, takes two ints
    Functor<float, int, int> func(&add, 2, 3);
    std::cout << func() << std::endl; // <-- Should print 5, make sense?
}

function has an unknown number of arguments until the functor is instantiated, but I think they're guaranteed to match the function signature, because I used the same variadic template to create them both (meaning it wouldn't compile if the function signature didn't match the template arguments). So, how do I store arguments so that I can pass them to function later?

Community
  • 1
  • 1
Joshua Hyatt
  • 1,300
  • 2
  • 11
  • 22
  • Why not use `std::bind` directly (or lambda) ? And for your argument problem, you may use `std::tuple` (and `std::index_sequence` for unwrapping it with `std::get`). – Jarod42 Dec 21 '15 at 23:05
  • Sorry, I'm not familiar with any of those. Would you please elaborate? – Joshua Hyatt Dec 21 '15 at 23:09
  • [Demo](http://ideone.com/muCVRT) for `std::bind` and lambda. – Jarod42 Dec 21 '15 at 23:15
  • @Jarod42 Thank you for responding. Could you post this as an answer with code? Meanwhile, I will continue to explore C++11. – Joshua Hyatt Dec 21 '15 at 23:38
  • That may fix your problem, but it is not the answer to your question (which uses `std::tuple` or similar). – Jarod42 Dec 21 '15 at 23:41
  • 1
    @Josh Answer already is on SO: http://stackoverflow.com/questions/7858817/unpacking-a-tuple-to-call-a-matching-function-pointer – Arpegius Dec 22 '15 at 00:01
  • Fantastic! It's a little hard to find, anything to be done about that? I searched for a long time before I asked this. – Joshua Hyatt Dec 22 '15 at 00:34

0 Answers0