C++ 中指向成员函数的函数指针
我需要调用一个需要函数指针的方法,但我真正想传递给它的是一个函子。这是我想做的一个例子:
#include <iostream>
#include "boost/function.hpp"
typedef int (*myAdder)(int);
int adderFunction(int y) { return(2 + y); }
class adderClass {
public:
adderClass(int x) : _x(x) {}
int operator() (int y) { return(_x + y); }
private:
int _x;
};
void printer(myAdder h, int y) {
std::cout << h(y) << std::endl;
}
int main() {
myAdder f = adderFunction;
adderClass *ac = new adderClass(2);
boost::function1<int, int> g =
std::bind1st(std::mem_fun(&adderClass::operator()), ac);
std::cout << f(1) << std::endl;
std::cout << g(2) << std::endl;
printer(f, 3);
printer(g, 4); // Is there a way to get this to work?
}
我一直无法找到一种方法来编译最后一行 print(g, 4) 。有办法让它发挥作用吗?我唯一能控制的是方法“main”和类“adderClass”。
I need to call a method that expects a function pointer, but what I really want to pass to it is a functor. Here's an example of what I'm trying to do:
#include <iostream>
#include "boost/function.hpp"
typedef int (*myAdder)(int);
int adderFunction(int y) { return(2 + y); }
class adderClass {
public:
adderClass(int x) : _x(x) {}
int operator() (int y) { return(_x + y); }
private:
int _x;
};
void printer(myAdder h, int y) {
std::cout << h(y) << std::endl;
}
int main() {
myAdder f = adderFunction;
adderClass *ac = new adderClass(2);
boost::function1<int, int> g =
std::bind1st(std::mem_fun(&adderClass::operator()), ac);
std::cout << f(1) << std::endl;
std::cout << g(2) << std::endl;
printer(f, 3);
printer(g, 4); // Is there a way to get this to work?
}
I haven't been able to find a way to get the last line, printer(g, 4), to compile. Is there a way to get this to work? The only things in my control are the method "main" and the class "adderClass".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好的,这是另一个尝试:
问题是您将
printer
编译为必须接收函数指针而没有其他任何内容,因此您必须向其发送函数指针。使用函数指针,就没有人可以保存您的实例。因此,该解决方案通过使用静态数据成员来实现这一点。请注意,这使得该代码不是线程安全的。同时执行
main
的两个线程可能会在m_instance中放入两个不同的东西。Ok, here's another try:
The trouble is that you have
printer
compiled as having to receive a function pointer and nothing else so you must send it a function pointer. With a function pointer you have no one to hold your instance. So this solution does that by using a static data member.Mind you that this makes this code not thread safe. Two threads which execute
main
at the same time may put two different things in m_instance.像这样:
此外,您不需要
boost::function
。你可以这样做:like so:
Also, you don't need the
boost::function
. You can just do:虽然 boost 函数的行为类似于普通函数指针,但它是不同的类型。所以你不能只将 boost 函数分配给函数指针。
在您的代码中,您可以简单地替换
为
,一切都会正常。
While a boost function behaves like a normal function pointer, it is a different type. So you can't just assign a boost function to a function pointer.
In your code you could simply replace
with
and everything would work.