3

I have a static function foo but the API I want to call only accept pointer to a functor (of similar interface ). Is there a way to pass foo to the API? or I need to re-implement foo in terms of functor.

Example code:

template<typename ReturnType, typename ArgT>
struct Functor: public std::unary_function<ArgT,ReturnType>
{
    virtual ~Functor () {}
    virtual ReturnType operator()( ArgT) = 0;
};


// I have a pre written function
static int foo (int a) {
    return ++a;
}

// I am not allowed to change the signature of this function :(     
static void API ( Functor<int,int> * functor ) {
    cout << (*functor) (5);
}

int main (void) {
    API ( ??? make use of `foo` somehow ??? );
    return 0;
}

My question is for calling API, implementing Functor is only solution or there is a way by which I could use foo to pass it to API?

Will boost::bind help here?
I mean boost::bind(foo, _1) will make function object out of foo and then if there is a way to form desired functor out of function object?

Vishnu Kanwar
  • 761
  • 5
  • 22

1 Answers1

2

It seems like you have no option other than writing your own functor as a derived type of Functor<int, int>. However, you could save yourself some trouble by providing an intermediate class template functor that can be instantiated from a functor or funciton pointer:

template<typename R, typename A>
struct GenericFunctor<R, A> : public Functor<R, A>
{
    template <typename F>
    MyFunctor(F f) : f_(f) {}
    ReturnType operator()(A arg) = { return f_(arg);}
private:
    std::function<R(A)> f_; // or boost::function
};

Then you can say

GenericFunctor<int, int> fun = foo;
API(&fun);  // works. GenericFinctor<int,int> is a Functor<int,int>

This is just a workaround for the fact that the stuff you have been given is so awful.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • Thanks for making it bold that it is not possible and implementing Functor is only solution. I wonder why people rank down a question all of a sudden while it could have negative answer which is also helpful. – Vishnu Kanwar Nov 05 '13 at 07:01
  • @VishnuKanwar you are implementing `Functor`. Using inheritance. – juanchopanza Nov 05 '13 at 07:02
  • Thanks a ton `juanchopanza` looks like a nice intermediate solution. – Vishnu Kanwar Nov 05 '13 at 07:07
  • I would like to request you to give your expert comments on this question sir: http://stackoverflow.com/questions/19269438/is-there-a-way-to-call-member-function-without-operator – Vishnu Kanwar Nov 06 '13 at 05:50