patterncppCritical
Using generic std::function objects with member functions in one class
Viewed 0 times
functionswithfunctionclassmemberstdusingobjectsgenericone
Problem
For one class I want to store some function pointers to member functions of the same class in one
I receive
map storing std::function objects. But I fail right at the beginning with this code:#include
class Foo {
public:
void doSomething() {}
void bindFunction() {
// ERROR
std::function f = &Foo::doSomething;
}
};I receive
error C2064: term does not evaluate to a function taking 0 arguments in xxcallobj combined with some weird template instantiation errors. Currently I am working on Windows 8 with Visual Studio 2010/2011 and on Win 7 with VS10 it fails too. The error must be based on some weird C++ rules i do not followSolution
A non-static member function must be called with an object. That is, it always implicitly passes "this" pointer as its argument.
Because your
If you want to bind a function with parameters, you need to specify placeholders:
Or, if your compiler supports C++11 lambdas:
(I don't have a C++11 capable compiler at hand right now, so I can't check this one.)
Because your
std::function signature specifies that your function doesn't take any arguments (``), you must bind the first (and the only) argument.std::function f = std::bind(&Foo::doSomething, this);If you want to bind a function with parameters, you need to specify placeholders:
using namespace std::placeholders;
std::function f = std::bind(&Foo::doSomethingArgs, this, std::placeholders::_1, std::placeholders::_2);Or, if your compiler supports C++11 lambdas:
std::function f = [=](int a, int b) {
this->doSomethingArgs(a, b);
}(I don't have a C++11 capable compiler at hand right now, so I can't check this one.)
Code Snippets
std::function<void(void)> f = std::bind(&Foo::doSomething, this);using namespace std::placeholders;
std::function<void(int,int)> f = std::bind(&Foo::doSomethingArgs, this, std::placeholders::_1, std::placeholders::_2);std::function<void(int,int)> f = [=](int a, int b) {
this->doSomethingArgs(a, b);
}Context
Stack Overflow Q#7582546, score: 441
Revisions (0)
No revisions yet.