Why can't I pass the this pointer explicitly to a member function?

巧了我就是萌 提交于 2019-12-05 06:20:48

Lets add a static member to the class as:

 class foo{
    public:
         void bar()     { cout<<"hey there"<<endl; }
         static void bar(foo*) { cout<<"STATIC MEMBER"<<endl; }
};

Now if you write this:

 foo::bar(&obj); //static or non-static?

Which function should be called? In such situation, how would you call both of them? What would be the syntax? If you allow one function to have this syntax, you've to abandon it (i.e syntax) for other function. The Standard decided to have foo::bar(&obj) syntax for static member function, while abandoning it for non-static member function.


Anyway, if you want to pass &obj as argument to the non-static member function, then you can use type-erasure facilitated by std::function as:

 void (foo::*pbar)() = &foo::bar; //non-static member function   #1

 std::function<void(foo*)> bar(pbar); 

 bar(&obj); //same as obj.bar();

Likewise, you could call static member function as:

 void (*pbar)(foo*) = &foo::bar; //static member function            #2

 std::function<void(foo*)> bar(pbar); 

 bar(&obj); //same as foo::bar(&obj);

Note that at lines #1 and #2, the types of the object pbar makes the compiler to choose the correct member function — in the first case, it takes the pointer to the non-static member-function while in the latter case, it takes the pointer to the static member function.

Hope that helps.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!