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

浪尽此生 提交于 2019-12-22 05:13:37

问题


The c++ standard (ISO c++11) mentions in Section 9.3.1 that

A non-static member function may be called for an object of its class type, or for an object of a class derived (Clause 10) from its class type, using the class member access syntax (5.2.5, 13.3.1.1).

An attempt to compile this code with g++ (version 4.8.2)

 class foo{
    public:
         void bar(){
            cout<<"hey there"<<endl;
         }
};
int main(){
    foo obj;
    foo::bar(&obj);
}

gives a compile time error because it couldn't match the function's signature. I guess that is expected given what the standard states about calling member functions. Since the method will eventually take a form similar to bar(foo*) during some stage of compilation, why does the standard asks for member access syntax to call the member function?


回答1:


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.



来源:https://stackoverflow.com/questions/26667756/why-cant-i-pass-the-this-pointer-explicitly-to-a-member-function

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