0

I am passing a pointer to a member function into a template function. Something like this,

    Foo bar; /* bar.baz(...) is a function */
    auto pnt = bar.baz;

    passMmbFunc<...,decltype(pnt)>(...,pnt);

The relevant parts of passMmbFunc look like this,

   template <..., typename D>
   void map(..., D func) {
     ...
     auto ret = func(someVal);
     ...
   }

I assumed that the syntax for calling a pointer to a member function is the same as a regular pointer to function but it is not. I get the following error,

    error: must use '.*' or '->*' to call pointer-to-member function in 'func (...)', e.g. '(... ->* func) (...)'

From within passMmbFunc, how would I call pnt? I know that a pointer to a member function can be called if you have a object of the respective class handy. But since I am passing it as a parameter, that is not the case. So, is there anyway to call a pointer to member function if you only have a pointer and no object?

  • You made a wrong assumption. – dtech Apr 26 '15 at 19:47
  • The syntax is tripping you up because (as the previous comment suggested) you assumed too much. You cannot call a pointer to a non-static member function without an object, and the syntax ensures that. – PaulMcKenzie Apr 26 '15 at 19:48
  • What would invoking a member function like `size()` or `to_string()` or whatever mean without an instance of the relevant class? – Mat Apr 26 '15 at 19:49
  • Ah, I see. Calling the function wouldn't make sense outside the context of an object. So it would work if the member function was static? –  Apr 26 '15 at 19:50
  • @sguzman If the function is static, then yes, you can call it without an instance of the object. – PaulMcKenzie Apr 26 '15 at 19:51
  • @ddriver Turns out my question is a duplicate. I'll mark it as such. –  Apr 26 '15 at 19:53

1 Answers1

0

A pointer-to-member function must be called on an object - it cannot work as a standalone function. Hence your error. baz must be called with some Foo using either the .* or ->* syntax:

auto ptr_to_mem = &Foo::baz;
Foo f, *pf;

ptr_to_mem();        // error
(f.*ptr_to_mem)();   // ok
(pf->*ptr_to_mem()); // ok

The way to do this in C++ is to bind the pointer-to-member with an object that you will call it with. The standard even provides a function to do that: std::bind:

auto pnt = std::bind(&Foo::baz, bar);
pnt(); // this is the equivalent of bar.baz();

One possible source of confusion is that auto pnt = bar.baz; will actually do exactly what you want in Python. Just not in C++.

Barry
  • 286,269
  • 29
  • 621
  • 977