Search code examples
c++pointer-to-member

Using member function without taking address?


class C{
public:
  int i(){return 3;}
};

void memfn(int (C::* const & func)()){}
void fn(int (* const & func)()){}

int main() {
  fn(&foo); //Works
  fn(foo); //Works
  memfn(&C::i); //Works
  memfn(C::i); //Doesn't Work
}

When passing a function pointer as a parameter, the address-of operator is optional on the function. Why does it not work if removed on a member function?


Solution

  • There is an implicit conversion from global function references, or static member function references, or non-capturing lambdas, to function pointers. This is for capability with C.

    But such implicit reference-to-pointer conversions are not for non-static member functions (and capturing lambdas!), because they need an implicitly passed this pointer to work, the conversion just lacks that thing.

    In your case, if we make i() static, then it can be passed to fn either by reference or by address.