C++仿函数模板

ste*_*225 0 c++ templates functor

给定以下类,它只是将内部函子映射f到稍后要运行的函数:

class A {
private:
   int (A::*f)(int);
   int foo(int x) { return x; }
   int bar(int x) { return x*2; }
public:
   explicit A(bool foo=true) { f = foo ? &A::foo : &A::bar; }
   int run(int x) { return (this->*f)(x); }
};
Run Code Online (Sandbox Code Playgroud)

现在说我有另一堂课,B:

class B {
public:
   int foo(int) { return x*x; }
};
Run Code Online (Sandbox Code Playgroud)

功能foo:

int foo(int x) { return 0; }
Run Code Online (Sandbox Code Playgroud)

我知道这是不可能有A分配和运行B::foo或者foo作为他们的原型不同:int (A::*)(int)VS int (B::*)(int)VS int (*)(int).

我要问的是,他们是否有任何方式来模板化A::f以便可以采取任何一种方法?

Pup*_*ppy 6

通常,您使用std::/ boost::/ std::tr1 ::function<int(int)>进行此类工作.它可以使任何具有正确签名的函数对象(包括指针).您可以创建使用bind相同包中的成员函数调用的函数对象.