c++ - How to use bind correctly here? -
i can not figure out correct syntax bind member functions. if have function takes function single argument, how pass object it?
in following example, correct syntax of passing function?
#include <iostream> #include <functional> void caller(std::function<void(int)> f) { f(42); } class foo { public: void f(int x) { std::cout<<x<<std::endl; } }; int main() { foo obj; caller(std::bind(&foo::f,obj)); //^wrong }
error was:
a.cpp: in function ‘int main()’: a.cpp:18:34: error: not convert ‘std::bind(_func&&, _boundargs&& ...) [with _func = void (foo::*)(int); _boundargs = {foo&}; typename std::_bind_helper<std::__or_<std::is_integral<typename std::decay<_tp>::type>, std::is_enum<typename std::decay<_tp>::type> >::value, _func, _boundargs ...>::type = std::_bind<std::_mem_fn<void (foo::*)(int)>(foo)>]((* & obj))’ ‘std::_bind_helper<false, void (foo::*)(int), foo&>::type {aka std::_bind<std::_mem_fn<void (foo::*)(int)>(foo)>}’ ‘std::function<void(int)>’ caller(std::bind(&foo::f,obj));
placeholders create "space" actual arguments bound later:
int main() { foo obj; caller(std::bind(&foo::f, &obj, std::placeholders::_1)); // ^ placeholder // ^ address or foo() }
these placeholders needed correctly generate appropriate signature std::bind
result bound std::function<void(int)>
.
you may want use address of object, or std::ref
(so won't copied); vary on want semantics be.
Comments
Post a Comment