Passing a variadic function as an argument?

Started by
3 comments, last by louie999 7 years, 6 months ago

Hi,

So, I'm a bit lost here, how exactly can I make a function that can accept another (variadic) function as an argument? Something like:


ExecuteFunc(Func1("blah"))
ExecuteFunc(Func2(1, 2, "blahblah"))

If I'm not mistaken, it has something to do with the "<functional>" library and templates, right?

Thanks in advance...

Advertisement

You can e.g. wrap your 'variadic function' inside a lambda function and make your exec function accept this lambda:


#include <iostream>
#include <functional>

void ExecuteFunc(std::function<void()> fn) { fn(); }

void Func1(std::string s) { std::cout << "Func1(" << s << ")" << std::endl; }
void Func2(int a, int b, std::string s) { std::cout << "Func2(" << a << ", " << b << ", " << s << ")" << std::endl; }

void main()
{
    ExecuteFn([]() { Func1("foo"); });
    ExecuteFn([]() { Func2(1, 2, "bar"); });
}

Thank you so much chingo! :D That function is what exactly I've been looking for.

Are you sure you want to do something like that?
Even for simple functions it becomes quickly unreadable and if the argument function is variadic you also risk to lose what is what.

Well, I need it for my GUI system. I have a "Button" class so whenever it'll get clicked then it'll call a specific function. Though, I added some stuff to it and tested it, seems to be working:


#include <iostream>
#include <functional>

#include <string>

 

class Caller

{

    public:

        std::function<void()> func;

 

        Caller();

        void ExecFunc(std::function<void()> f);

        void CallFunc();

        void SetFunc(std::function<void()> f);

};

 

Caller::Caller() {}

 

void Caller::CallFunc()

{

    ExecFunc(func);

}

 

void Caller::ExecFunc(std::function<void()> f)

{

f();

}

 

void Caller::SetFunc(std::function<void()> f)

{

    func = f;

}

 

void test(std::string str)

{

std::cout << str << std::endl;

}

 

int main()

{

    Caller caller1;

    Caller caller2;

 

    caller1.SetFunc([](){test("string");});

    caller2.SetFunc([](){test("lol");});

 

    caller1.CallFunc();

    caller2.CallFunc();

}

That way, I can store a function to the class and call it later on. Though, will that cause some problems? Like memory leaks or anything?

This topic is closed to new replies.

Advertisement