Problems with "bind" and "function"

A back, I came across the question of how to pass the called function returned by bind (let's call it A) to another function (let's call it B), which expects a parameter that is a pointer to a function from A. I found that the called A returned bind, has a very complex type and therefore abandoned my approach.

Then I found out about the β€œfunction” in the function header, which sounded as if it had solved my problem. However, after several attempts, I was again thwarted! Maybe you can help? Here is the 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 want to do is first create a new callable with bind, and then send this related function to another function as a parameter. If possible, I do not want to deal with the messy type returned by bind.

I am open to alternative approaches to solving this problem.

+4
source share
3 answers

Try auto f = [](int n) -> int { return parab(n, 0); }; auto f = [](int n) -> int { return parab(n, 0); };

This should work with funk(-5, f) (since non-locking locks are converted to function pointers).

bind and function have their place, but they are not always the best choice.

+4
source

Type std::function , which takes int and returns int , std::function<int(int)> not std::function<int(*)(int)> .

Secondly, std::function cannot be converted to a function pointer. Change the funk interface to int funk(int a, std::function<int(int)>) if you want to pass it std::function or make it a template argument of an unknown type.

Thirdly, if you use an idle lambda, then this can be passed to a function that uses a function pointer. Barren lambdas are lambda types that don't capture anything - they [] have nothing in square brackets. Your binding expression can be rewritten as stateless lambda in this case, because your binding is a known compile-time value.

+2
source

f not int (*f)(int) . This is an unspecified functor. But it can be used as a function. So just type tpe in funk

 template<typename F> int funk(int a, F f) { return f(a); } 
+2
source

Source: https://habr.com/ru/post/1489591/


All Articles