Arbitrary class method pointer

Say I have:

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

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

 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 in which I can create a template for any pointer to a class method? I want to be able to:

 works_for_anything<&Foo::a>(&some_foo); works_for_anything<&Foo::b>(&some_foo, 42); int result = works_for_anything<&Foo::c>(&some_foo); 
+6
source share
1 answer

Will this work for you?

 template< typename T, T > class works_for_anything_t; template< typename R, typename... Args, R (*f)(Args...) > class works_for_anything_t< R (*)(Args...), f >{ public: R operator()( Args... args ){ return f(args...); } }; template< typename T, typename R, typename... Args, R (T::*f)(Args...) > class works_for_anything_t< R (T::*)(Args...), f >{ public: R operator()( T& v, Args... args ) { return (v.*f)(args...); } works_for_anything_t(T& v) : v_(v) { } private: T& v_; }; template< typename T, typename R, typename... Args, R (T::*f)(Args...) const > class works_for_anything_t< R (T::*)(Args...) const, f >{ public: R operator()( const T& v, Args... args ) const { return (v.*f)(args...); } works_for_anything_t(const T& v) : v_(v) { } private: const T& v_; }; #define works_for_anything(f) works_for_anything_t<decltype(&f), &f> struct Foo { void a(); void b(const int& ); int c(); }; int test(); int main() { Foo foo; works_for_anything(Foo::b){foo}( 42 ); works_for_anything(test){}(); return 0; } 
0
source

Source: https://habr.com/ru/post/982003/


All Articles