A while back, I ran into the question of how to pass a callable returned by bind (call it A) to another function (call it B) which expects a parameter which is a pointer to a function of the from A. I discovered that a callable A returned by bind has a very complicated type and so gave up on my approach.
Then I learned about 'function' in the functional header which sounded as if it would solve my problem. However, after a few attempts, I was again thwarted! Perhaps you can help? Here is some code that will not work:
#include <iostream>
#include <functional> //Library for "bind" and "function"
#include <cmath>
using namespace std;
using namespace std::placeholders; //for _1, _2, _3 ...
//praboloid function
int parab(int x, int y) {
return pow(x,2) + pow(y,2);
}
//Take an integer and a pointer to a function
int funk(int a, int (*f)(int) ) {
return (*f)(a);
}
int main() {
auto f = bind(parab, _1, 0); // Bind the second value to 0
function<int (int)> fp = f;
//Any of the following lines creates and error
function<int (*)(int)> fp = f; //Error!
funk(-5, f); //Error!
funk(-5, &f); //Error!
funk(-5, fp); //Error!
funk(-5 &fp); //Error!
return 0;
}
All I wish to do is first create a new callable using bind and then send that bound function to another function as a parameter. If possible, I don't want to have to deal with the messy type returned by bind.
I am open to alternate approaches to solving this problem.
Try auto f = [](int n) -> int { return parab(n, 0); };
That should work with funk(-5, f)
(because non-capturing closures are convertible to function pointers).
bind
and function
have their place, but they're not always the best choice.
f
is not int (*f)(int)
. It's functor of unspecified type. But it can be used as a function. So just get any tpe in funk
template<typename F>
int funk(int a, F f) {
return f(a);
}
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