Why can't I pass the this pointer explicitly t

2019-04-29 03:33发布

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?

标签: c++ c++11 this
1条回答
Explosion°爆炸
2楼-- · 2019-04-29 04:21

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.

查看更多
登录 后发表回答