Reference to member function? [duplicate]

2019-06-15 04:35发布

问题:

This question already has an answer here:

  • Why doesn't reference-to-member exist in C++? 1 answer

I recently find out that there is a reference-to-function concept in C++ :). So as there are pointer-to-function and pointer-to-member-function different types. The question arises. Is there a "reference-to-member-function" concept?

I tried to compile the following code, but GCC 3.4.6 gives an error.

#include <iostream>

using namespace std;

class A {
public:
  virtual void Af() const {
    cout << "A::Af()" << endl;
  }
};

int main() {
  typedef void (A::& MemFnc)() const;
  MemFnc mf = &A::Af;

  A a;
  (a.*mf)();

  return 0;
}

回答1:

There is no such a thing called reference to member in C++.

The language specification explicitly says in a note (§8.3.3/3 - 2003) that,

A pointer to member shall not point to a static member of a class (9.4), a member with reference type, or “cv void.” [Note: see also 5.3 and 5.5. The type “pointer to member” is distinct from the type “pointer”, that is, a pointer to member is declared only by the pointer to member declarator syntax, and never by the pointer declarator syntax. There is no “reference-to-member” type in C++.



回答2:

There is no reference to member function.



回答3:

No, references to member functions are not possible.

In some sense, the result of dereferencing a pointer to a member function could serve as one, but the only thing you can do with that result is to invoke a function call operator on it, per 5.5[expr.mptr.oper]/6. Nothing else is allowed.