mercredi 4 février 2015

Template non-type pointer to arbitrary class method

Let's say I have:



struct Foo {
void a();
void b(const int& );
int c();
};


I can create a function that takes as an argument an arbitrary pointer-to-Foo method:



template <typename R, typename... Formal, typename... Args>
R call(Foo* f, R (Foo::*method)(Formal...), Args&&... args) {
return (f->*method)(std::forward<Args>(args)...);
}

int gratuitous = call(&some_foo, &Foo::c);


And I can create a function that takes a specific type of pointer-to-Foo method as a template:



template <void (Foo::*method)()>
void only_for_a(Foo *f) {
(f->*method)();
}

only_for_a<&Foo::a>(&some_foo);


But is there a way to create a function that I can template on any pointer to class method? I want to be able to do:



works_for_anything<&Foo::a>(&some_foo);
works_for_anything<&Foo::b>(&some_foo, 42);
int result = works_for_anything<&Foo::c>(&some_foo);

Aucun commentaire:

Enregistrer un commentaire