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

The C ++ Standard (ISO C ++ 11) mentions section 9.3.1 , which

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

Attempting 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 cannot match the function signature. I assume this is expected given that the standard claims to call member functions. Since the method will eventually take on a form similar to bar (foo *) at some stage of compilation, why does the standard request member access syntax to call a member function?

+5
source share
1 answer

Allows you to 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? 

What function should be called? In such a situation, what would you call them both? What will be the syntax? If you allow one function to have this syntax, you must abandon it (for example, syntax) for another function. The standard decided to have the syntax foo :: bar (& obj) for the static member function, leaving it for the non-static member function.


In any case, if you want to pass &obj as an argument to a non-static member function, you can use type erase, simplified by std::function , like:

  void (foo::*pbar)() = &foo::bar; //non-static member function #1 std::function<void(foo*)> bar(pbar); bar(&obj); //same as obj.bar(); 

Similarly, you can call a 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 in lines #1 and #2 types of the pbar object force the compiler to select the correct member function - in the first case, it takes a pointer to a non-stationary member function, and in the latter case, it takes a pointer to a static member function.

Hope this helps.

+6
source

Source: https://habr.com/ru/post/1205919/


All Articles