How to skip an argument using <functional> in C ++ 11/98

Let's say I have a function:

void function() {
    cout << "Hello!" << endl;
}

      

And I have an algorithm that calls a function and passes two arguments to it:

template <class F>
void my_algorithm(F f) {
    // ...
    f(x, y);
    // ...
}

      

How to pass function

in my_algorithm

by manipulating a function or function object without manually creating a wrapper? For reference, the shell I don't want to create would look like this:

void functionSkipArgs(A a, B b) {
    function();
}

      

In other words, I would like to find a function or series of functions that match some_operations

in the following code:

my_algorithm(some_operations(&function));

      

+3


source to share


3 answers


This seems to work: http://ideone.com/6DgbA6



#include <iostream>
#include <functional>

using namespace std;


void func() {
    cout << "Hello!" << endl;
}

template<class F>
void my_algorithm(F f) {
    int x = 100;
    int y = 200;

    f(x, y);
}


int main() {

    my_algorithm(std::bind(func));

    return 0;
}

      

+5


source


In C ++ 11, which is your question, use lambda . Here's the code:

my_algorithm([](A, B) 
{ 
    return function();
});

      

What the lambda does for you is it creates that wrapper for yours.



If you want this to be templated and you have C ++ 14 then you can use auto:

my_algorithm([](auto, auto) 
{ 
    return function();
});

      

+3


source


Solution using std::function

and lambda:

#include <iostream>
#include<functional>

void function() {
    std::cout << "Hello!" << std::endl;
}

template <typename F>
void my_algorithm(F f) {    
    int x=0;
    int y=10;
    f(x, y);    
}

int main()
{  
    std::function<void(int,int)> fun= [](int x, int y){  function();};        
    my_algorithm(fun);
}

      

0


source







All Articles