C++函子模板
给定以下类,它简单地将内部函子 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); }
};
现在假设我有另一个类, B
:
class B {
public:
int foo(int) { return x*x; }
};
和函数 foo< /code>:
int foo(int x) { return 0; }
我知道不可能让 A
分配并运行 B::foo
或 foo
因为它们的原型不同:int (A::*)(int)
与 int (B::*)(int)
与 int (*)(int)
。
我要问的是,他们有什么方法可以模板化 A::f
以便它可以采用其中任何一个吗?
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 templatize A::f
such that it could take any of them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常,您使用
std::
/boost::
/std::tr1
::function;
对于这种工作。它可以采用具有正确签名的任何函数对象(包括指针)。您可以使用同一个包中提供的bind
创建调用成员函数的函数对象。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 usingbind
, available in the same package.我不太确定你想要实现什么,但你可能想看看:
I am not exactly sure what you are trying to achieve, but you may want to look into: