Can I store bound functions in a container?

323 views Asked by At

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();
}
2

There are 2 answers

0
Geezer On BEST ANSWER

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

0
AnT stands with Russia On

std::bind is not guaranteed to return the same type for functions with the same final interface (final = after binding). So, no, you won't be able to store functions bound with std::bind in a container. You will have to use some sort of type-erasure technique to bring them all to the same type, like std::function. A container of std::function<void()> will be able to store your bound functions (at the expense of type-erasure-related overhead).

I don't know whether it applies to boost::bind, but I suspect it is the same as std::bind in that regard.