I'm trying to create a vector of std::function and then pass that vector to a function. I also need to pass arguments to the function objects, so I'm using std::bind. Here is the code:
#include <functional>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void execute(vector<function<void (int)>>& fs) {
for (auto& f : fs)
f();
}
void func(int k) {
cout << "In func " << k << endl;
}
int main()
{
int i = 1;
vector<function<void (int)>> x;
auto f1 = bind(func, i);
x.push_back(f1);
execute(x);
}
but this gives following error:
function_tmpl.cpp: In function ‘void execute(std::vector >&)’: function_tmpl.cpp:14:5: error: no match for call to ‘(std::function) ()’ f(); ^ In file included from function_tmpl.cpp:1:0: /usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/functional:2142:11: note: candidate is: class function ^ /usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/functional:2434:5: note: _Res std::function::operator()(_ArgTypes ...) const [with _Res = void; _ArgTypes = {int}] function:: ^ /usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/functional:2434:5: note: candidate expects 1 argument, 0 provided
If I call f() inside main(), that works fine, which means that the function has bound with the arguments, but it's not working when passed to another function as argument
Aucun commentaire:
Enregistrer un commentaire