c++boost-bind

Can I store bound functions in a container?


Consider the following code:

void func_0()
{
    std::cout << "Zero parameter function" << std::endl;
}

void func_1(int i)
{
    std::cout << "One parameter function [" << i << "]" << std::endl;
}

void func_2(int i, std::string s)
{
    std::cout << "One parameter function [" << i << ", " << s << "]" << std::endl;
}

int main()
{
    auto f0 = boost::bind(func_0);
    auto f1 = boost::bind(func_1,10);
    auto f2 = boost::bind(func_2,20,"test");

    f0();
    f1();
    f2();
}

The above code works as intended. Is there any way I can store f0, f1, f2 in a container and execute it like this:

Container cont; // stores all the bound functions.
for(auto func : cont)
{
    func();
}

Solution

  • Will this example work for you?

    std::vector<std::function<void()>> container{f0, f1, f2};
    for (auto& func : container)
    {
        func();
    }
    

    You can read here about std::function:

    Instances of std::function can store, copy, and invoke any Callable target ...

    So the template argument for this class template (void() in our case) is merely the signature of the Callable. What bind() returned in all your calls to it is exactly a Callable of the form void().