c++: std::vector of std::function with arbitrary signatures

c++, function, vector

Solution

This should work:

#include <iostream>
#include <functional>
#include <vector>

void hello() { std::cout << "Hello\n"; }
void hello2(const char * name) { std::cout << "Hello " << name << '\n'; }

int main()
{

    std::vector<std::function<void()>> v;
    v.push_back(hello);
    v.push_back(std::bind(hello2, "tim"));
    v[0]();
    v[1]();
}

How are you doing it?

Problem

Is it possible to create an `std::vector` that can hold an `std::function` with any signature? (The function arguments would all be pre-bound.) I tried `std::vector<std::function<void()> >`, since if I only have one `std::function` of that type I can bind any function to it. This does not seem to work inside a vector: if I try to add a function with `std::bind` to the vector that has a signature other than `void()`, I get: ``` No matching member function for call to 'push_back' ``` Is there a way to do this? Edit: I just remembered that `std::function<void()>` does allow you to bind any function that returns `void` as long as the arguments are pre-bound with `std::bind`, it does not allow you to bind any signature though, but for my purposes it's generic enough, so the following works: ``` class A { public: void test(int _a){ return 0; }; }; A a; std::vector<std::function<void()> > funcArray; funcArray.push_back(std::bind(&A::test, std::ref(a), 0)); ```

Original source