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

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

最佳答案

这对你有用吗?

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

关于c++ - 指向任意类方法的模板非类型指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28332147/

相关文章:

c++ - 仅使用键作为比较器将两个 map 相交

c++ - 将 SampleGrabber 与 CaptureGraphBuilder2 结合使用时出现问题

c++ - 什么是 MPL 值习语?

c++ - 为什么这个函数会产生不正确的值?

c++ - 如何从 C++ 中的 tm 对象获取星期几?

c++ - 标题中的全局变量和函数

c++ - 多进程打开同一个文件导致文件操作失败

c++ - 将值插入以不同方式排序的两个BST中

c++ - 避免在此模板代码中创建变量

c++ - 将类的 move 成员作为const引用参数传递