模板非类型指向任意类方法的指针

时间:2015-02-04 21:49:53

标签: c++ templates c++11

让我说我有:

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

我可以创建一个函数,该函数将任意指针作为参数 - Foo方法:

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);

我可以创建一个函数,将特定类型的指针指向Foo方法作为模板:

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

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

但有没有办法创建一个函数,我可以在任何指向类方法的指针上进行模板化?我希望能够做到:

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

1 个答案:

答案 0 :(得分:0)

这对你有用吗?

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;
}