Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a member function needs '&' (e.g. in std::bind)?

Tags:

c++

c++11

When I was playing with std::bind from the C++11-standard I recognized the following would be allowed by the compiler:

class Foo
{
public:
  void F();
  int G(int, int);
};

void Foo::F()
{
  auto f = bind(&Foo::G, this, _1, _2);
  cout << f(1,2) << endl;
}

int Foo::G(int a, int b)
{
  cout << a << ',' << b << endl;
  return 666;
}

But if I eliminated the '&' in front of the Foo::G in the bind-line, I would get some compiler errors (using MinGW 4.7).

Why is Foo::G not valid as a pointer to a member function, although H and &H would both work for "usual" functions?

LG ntor

like image 229
Peter Wildemann Avatar asked Jan 20 '26 02:01

Peter Wildemann


2 Answers

& is required to take address of a member function, some compilers will allow you to omit the same but it is non-standard and at times confusing.

you can read about member function pointers in here: http://www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible

like image 157
Sarang Avatar answered Jan 21 '26 19:01

Sarang


I take it that one of the reasons could have been consistency. Recall that within a class, you can say

MyClassOrOneOfItsBases::memberFunction();

It compiles fine, since the qualified name names the member function, instead of forming a pointer to member.

like image 42
Johannes Schaub - litb Avatar answered Jan 21 '26 19:01

Johannes Schaub - litb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!