4

Is it possible to pass a class method as a parameter to a template? For example:

template<typename T, void(T::*TFun)()>
void call(T* x) {
    x->TFun();
}

struct Y {
    void foo();
};

int main() {
    Y y;
    call<Y,&Y::foo>(&y);  // should be the equivalent of y.foo()
}

If I try compiling the above, I get:

main.cpp: In instantiation of void call(T*) [with T = Y; void (T::* TFun)() = &Y::foo]:
main.cpp:12:23:   required from here
main.cpp:4:5: error: struct Y has no member named TFun
     x->TFun();
     ^

Is this possible and if so, what's the syntax?

Jerry
  • 394
  • 2
  • 8
  • 1
    This has nothing to do with templates. Try it with a regular member function pointer. – chris Aug 03 '14 at 17:59
  • 1
    [You may find **this** helpful](http://stackoverflow.com/questions/6586205/what-are-the-pointer-to-member-and-operators-in-c), particularly the syntax in the last line of the accepted answer. – WhozCraig Aug 03 '14 at 18:07
  • @WhozCraig, thanks for the link, if I had found that before, I wouldn't have had to ask here ;) – Jerry Aug 03 '14 at 18:12

1 Answers1

6

That's not how you refer to a pointer-to-member. You need to dereference it first:

(x->*TFun)();

I used parenthesis do deal with operator precedence issues. TFun will be dereferenced before it is called.

David G
  • 94,763
  • 41
  • 167
  • 253
  • Thanks. I thought I tried that syntax, but must have had it wrong or had some error. It compiles now, though. – Jerry Aug 03 '14 at 18:11