c++ - function pointer to a different class member -
i have following problem:
class { public: a() {} int foo(int a) { return a; } }; class b { private: int (a::*pfoo)(int); public: b(int (a::*_pfoo)(int)) { this->pfoo = _pfoo; } int cfoo(int i) { this->pfoo(i); //this causes problem compiler says it's not pointer } }; a; b b(&a::foo); i've tried already
int (*pfoo)(int) instead of
int (a::*pfoo)(int) but there problems constructor , when used b b(&a.foo) there compiler error says have use b b(&a::foo)
you trying call a:foo object of type b pointer member function of a requires instance of a.
instead of saving pointer or reference a inside b can redesign code b little more generic:
#include <functional> struct { int foo(int a) { return a; } }; class b { private: std::function<int(int)> pfoo; public: b(std::function<int(int)> foofunc) : pfoo(foofunc) { } int cfoo(int i) { return pfoo(i); } }; now b can take function pointer returning int 1 int argument , can bind function pointer a::foo instance of a:
a my_a; b my_b(std::bind(&a::foo, my_a, std::placeholders::_1)); my_b.cfoo(2); // works
Comments
Post a Comment