C++ functor templates
Given the following class, which simply maps an internal functor f
to a function to be run later:
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); }
};
Now say I have another class, B
:
class B {
public:
int foo(int) { return x*x; }
};
And function foo
:
int foo(int x) { return 0; }
I know it is not possible to have A
assign and run B::foo
or foo
as their prototypes differ: int (A::*)(int)
vs int (B::*)(int)
vs int (*)(int)
.
What I am asking, is their any way to te开发者_高级运维mplatize A::f
such that it could take any of them?
Normally, you use a std::
/boost::
/std::tr1
::function<int(int)>
for this kind of job. It can take any function object (including pointer) with the correct signature. You can create function objects that call member functions using bind
, available in the same package.
I am not exactly sure what you are trying to achieve, but you may want to look into:
- Boost.Function - can wrap any kind of callable
- Boost.Bind - can be used to bind a member function to an instance
精彩评论