Why member functions can't be used as template arguments?

Junekey Jeon picture Junekey Jeon · Jun 19, 2015 · Viewed 15.2k times · Source

Why member functions cannot be used as template arguments? For example, I want to do like:

struct Foo {
    void Bar() { // do something
    }
};
template <typename TOwner, void(&func)()>
void Call(TOwner *p) {
    p->func();
}
int main() {
    Foo a;
    Call<Foo, Foo::Bar>(&a);
    return 0;
}

I know that a similar thing can be done using pointers-to-member; well, it's cool enough most of the time, but I'm just curious about why pointers "should" be used.

I see no ambiguity of interpreting "p->func()" above. Why the standard prohibits us to use member functions as template arguments? Even static member functions are not allowed according to my compiler (VC++ 2013). Does anyone know the reason? Or, is there a way to do the same thing without loss of any performance due to pointer dereferencing?

Thank you.

Answer

user657267 picture user657267 · Jun 19, 2015

They can be used as non-type parameters, but you need to use the right syntax

struct Foo {
    void Bar() { // do something
    }
};
template <typename TOwner, void(TOwner::*func)()>
void Call(TOwner *p) {
    (p->*func)();
}
int main() {
    Foo a;
    Call<Foo, &Foo::Bar>(&a);
    return 0;
}