Home > database >  How do I pass a function as a parameter with it's own parameters in c
How do I pass a function as a parameter with it's own parameters in c

Time:11-05

Trying to call a function that gets used as an argument for another function, while passing it's own arguments. Example in pseudoish c code:

void function1(argument(x)) ///I believe this should be void function1(void(*argument)(int)), but i try to call it as *argument(); and that fails also
{
    doStuff;
    argument(x);
    doMoreStuff;
}

void function2(int x)
{
     int test;
     test = x   2;
     doOtherStuffWithx;
}

int main()
{
    int test = 1;
    sample = function1(function2(test));
}



haven't been able to figure it out. Any help would be greatly appreciated.

CodePudding user response:

The simplest for you would be to program it like that:

#include <functional>

void function1(std::function<void(int)> func, int arg)
{
    //doStuff;
    func(arg);
    //doMoreStuff;
}

void function2(int x)
{
     int test;
     test = x   2;
     //doOtherStuffWithx;
}

int main()
{
    int test = 1;
    function1(function2, test);
}

If you want to use some function with arbitrary number of arguments and types, then you can use templates:

template<typename F, typename... Args>
void function1(F&& func, Args&&... args)
{
    //doStuff;
    func(std::forward<Args>(args)...);
    //doMoreStuff;
}

CodePudding user response:

The simplest way to do this is to use a lambda expression calling the function with the desired parameter, and pass that as a std::function that your function1() accepts:

#include <iostream>
#include <functional>

void function1(std::function<void()> f)
{
    std::cout << "Stuff before...\n";
    f();
    std::cout << "... stuff after.\n";
}

void function2(int x)
{
     int test;
     test = x   2;
     std::cout << test << '\n';
}

int main()
{
    int test = 1;
    function1([=]() { function2(test); });
}
  •  Tags:  
  • c
  • Related