How to call a member function pointer which is assigned to a member function? I am learning callbacks and this is just for learning purpose. How I can invoke m_ptr function ?
class Test{
public:
void (Test::*m_ptr)(void) = nullptr;
void foo()
{
std::cout << "Hello foo" << std::endl;
}
};
void (Test::*f_ptr)(void) = nullptr;
int main()
{
Test t;
f_ptr = &Test::foo;
(t.*f_ptr)();
t.m_ptr = &Test::foo;
// t.Test::m_ptr(); //Does not work
// t.m_ptr(); //Does not work
// (t.*m_ptr)(); //Does not work
return 0;
}
You are almost there. Recall that m_ptr
is a data member itself, so in order to access it you need to tell the compiler to resolve that relationship to the instance holding the pointer to member. Call it like this:
(t.*t.m_ptr)();
// ^^ this was missing
如果您有C ++ 17,也可以
std::invoke(t.m_ptr, t);
Operator .*
requires expression that return a pointer to member of class-type on the right side and expression which object of that type on the left side (ie t
in your case). But your pointer is a member, so right expression should be t.m_ptr
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.