samedi 29 août 2015

std::bind syntax difference between global and member functions

When using std::bind, why is it that I must specify a & before a member function, but not before a global function? For instance, my main.cpp is:

  1 #include <functional>
  2 
  3 class Foo
  4 {
  5   public:
  6     void Exec(void) {}
  7 };
  8 
  9 void Exec(void) {}
 10 
 11 int main(void)
 12 {
 13   Foo inst;
 14   auto blah1 = std::bind(Exec);
 15   //auto blah2 = std::bind(Foo::Exec, &inst);
 16   auto blah2 = std::bind(&Foo::Exec, &inst);
 17   blah1();
 18   blah2();
 19   return 0;
 20 }

This compiles fine, but if I uncomment 15 and comment line 16, I get:

$ g++ main.cpp -o a.out -std=c++11 -Wall
main.cpp: In function ‘int main()’:
main.cpp:15:31: error: invalid use of non-static member function ‘void Foo::Exec()’
   auto blah2 = std::bind(Foo::Exec, &inst);

I really don't understand this error. I would have expected both instances to either require & or not, but they turned out to be treated differently. Can someone help me understand why the compiler is picky about this difference?

Aucun commentaire:

Enregistrer un commentaire