【问题标题】:c++ generic pointer to (member?) functionc++ 指向(成员?)函数的通用指针
【发布时间】:2010-05-20 12:20:45
【问题描述】:

我似乎无法声明指向函数的通用指针。

要调用这两个函数:

void myfunc1(std::string str)
{
    std::cout << str << std::endl;
}
struct X
{
        void f(std::string str){ std::cout<< str << std::endl;}
};

还有这两个函数调用者:

typedef void (*userhandler_t) (std::string);
struct example
{   
    userhandler_t userhandler_;

    example(userhandler_t userhandler): userhandler_(userhandler){}

    void call(std::string str)
    {   
        userhandler_(str);
    }
};
template<typename func_t>
void justfunc(func_t func)
{
    func("hello, works!");
}

当我尝试将它们与 boost::bind 一起使用来调用成员函数时,它们会给我编译错误。

这行得通:

example e1(&myfunc1);
e1.call("hello, world!");
justfunc(&myfunc1);

这不是:

X x;
example e2(boost::bind(&X::f, &x, _1));
e2.call("hello, world2!");
justfunc(boost::bind(&X::f, &x, _1));

这应该怎么做?

【问题讨论】:

  • X::f 的返回类型和参数类型都不匹配 example 的要求。你预计会发生什么?

标签: c++ function-pointers boost-bind member-function-pointers


【解决方案1】:

boost::bind 创建行为类似于函数的对象,而不是实际的函数指针。使用 Boost.Function 库保存调用boost::bind的结果:

struct example
{
    boost::function<void(std::string)> userhandler_;
    ...
};

【讨论】:

  • 正如 Marcelo 所说,boost::bind 创建函数对象(又名函子),而不是函数指针。来自我的 +1。
  • 谢谢,我在文档中错过了这一点(在这里:boost.org/doc/libs/1_43_0/libs/bind/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-24
  • 1970-01-01
相关资源
最近更新 更多