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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With