C ++ binding function to use as an argument to another function

I have a function that requires a function pointer as an argument:

int func(int a, int (*b)(int, int)) { return b(a,1); } 

Now I want to use a specific function with three arguments in this function:

 int c(int, int, int) { // ... } 

How to bind the first argument c so that I can:

 int i = func(10, c_bound); 

I looked at std::bind1st , but I can't figure it out. Does it not return the correct function pointer? I have complete freedom to adapt func , so any approach changes are possible. Althoug I would like the user of my code to be able to define his own c ...

Please note that the above is a severe simplification of the actual functions that I use.

The project, unfortunately, requires C++98 .

+6
source share
3 answers

You cannot do this. You will need to modify func to take the function object first. Sort of:

 int func( int a, std::function< int(int, int) > b ) { return b( a, rand() ); } 

Actually there is no need for b be std::function , it could be instead of templates:

 template< typename T > int func( int a, T b ) { return b( a, rand() ); } 

but I would stick with the std::function version for clarity and somewhat less confusing compiler output on errors.

Then you can do something like:

 int i = func( 10, std::bind( &c, _1, _2, some-value ) ); 

Note that this is C ++ 11 , but you can do it in C ++ 03 using Boost.

+12
source

Well, if you know at compile time what you need to associate c with, you can define a new function

 int c_bound(int a, int b) { return c(a,b,some_value); } 

This is clearly not a general solution, but may solve your current problem. Otherwise, the K-ballo solution seems to be the only simple common one. However, this requires that you can change the signature of func . If you really have an API that you cannot touch the signature, and you still need to bind an argument And if the above solution does not solve your specific case: (carefully, redundant) I always wanted to use the LLVM solution to compile the function at runtime and transmitting her address in such situations.

+1
source

You cannot use the function of argument 3 as the function of argument 2; Mostly because there is no real way to determine what the third parameter will do.

While the above answer will work, here is another option:

If one of the parameters for c() used in func is constant, you can write a wrapper function for c(int, int, int) :

 int d(int a, int b) { return c(a, b, 0); //use a constant parameter } 

or, if you can determine the third parameter from two given parameters, you can also try:

 int e(int a, int b) { int extra = 0; ///Determine extra from a, and b return c(a, b, c); } 
0
source

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


All Articles