Jump to content
  • Advertisement
Sign in to follow this  
louie999

Passing a variadic function as an argument?

This topic is 724 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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...

Share this post


Link to post
Share on other sites
Advertisement
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.

Share this post


Link to post
Share on other sites

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?

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!