尽管需要函数指针,但使用函数对象
我必须使用一些需要函数指针的遗留代码,比方说:
void LEGACY_CODE(int(*)(int))
{
//...
}
但是我拥有的功能是在函子内:
struct X
{
Y member;
X(Y y) : member(y)
{}
int operator()(int)
{
//...
}
};
我应该如何修改/包装类 X
以便 LEGACY_CODE
可以访问 X::operator()(int)
中的功能吗?
I have to use some legacy code expecting a function pointer, let's say:
void LEGACY_CODE(int(*)(int))
{
//...
}
However the functionality I have is within a functor:
struct X
{
Y member;
X(Y y) : member(y)
{}
int operator()(int)
{
//...
}
};
How should I modify/wrap class X
so that LEGACY_CODE
can access the functionality within X::operator()(int)
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你的问题没有意义。您想致电谁的接线员?
所以,简而言之,你不能。成员函数
X::operator()
并不是类本身的属性,而是与X
对象实例 相关联>。在此站点中搜索“成员函数”和“回调”,以了解解决相关问题的可能方法的范围。
提供免费功能的最原始且很可能不安全的解决方法是这样的:
你可以看到这是怎么回事......
Your question makes no sense. Whose operator do you want to call?
So, in short, you cannot. The member function
X::operator()
is not a property of the class alone, but rather it is tied to an object instance of typeX
.Search this site for "member function" and "callback" to get an idea of the spectrum of possible approaches for related problems.
The crudest, and quite possibly not-safe-for-use, workaround to providing a free function would go like this:
You can see where this is going...
一个简单的包装函数如下所示:
如果您希望能够将参数传递给仿函数本身,最简单的方法是使用 (brr) 全局变量将它们隐藏起来:
您可以使用带有静态方法的类来包装它,并且如果需要的话,可以是静态成员。
A simple wrapper function looks like:
If you want to be able to pass the parameters to the functor itself, the simplest way is to sneak them in using (brr) a global variable:
You can wrap it with a class with a static method and a static member if you want.
这是一种编译时解决方案。根据您的需要,这对您来说可能是一个太有限的解决方案。
Here's one compile-time solution. Depending on what you need, this might be a too limited solution for you.
线程安全版本,限制是不能在线程中使用不同的参数调用遗留代码。
恕我直言,人们无法摆脱全局存储。
A thread-safe version under the restriction that the legacy code is not called with different parameters in a thread.
IMHO, one cannot get rid of global storage.