【问题标题】:function pointer to functor指向函子的函数指针
【发布时间】:2013-11-05 06:19:38
【问题描述】:

我有一个静态函数foo,但我想调用的 API 只接受指向函子的指针(类似的接口)。有没有办法将foo 传递给 API?或者我需要在函子方面重新实现foo

示例代码:

template<typename ReturnType, typename ArgT>
struct Functor: public std::unary_function<ArgT,ReturnType>
{
    virtual ~Functor () {}
    virtual ReturnType operator()( ArgT) = 0;
};


// I have a pre written function
static int foo (int a) {
    return ++a;
}

// I am not allowed to change the signature of this function :(     
static void API ( Functor<int,int> * functor ) {
    cout << (*functor) (5);
}

int main (void) {
    API ( ??? make use of `foo` somehow ??? );
    return 0;
}

我的问题是调用 API,实现Functor 是唯一的解决方案,或者有一种方法可以使用foo 将其传递给API

boost::bind 会帮忙吗?
我的意思是boost::bind(foo, _1) 会从foo 中生成函数对象,然后是否有办法从函数对象中生成所需的函子?

【问题讨论】:

  • boost::bind 会提供什么方面的帮助吗?是否有什么东西阻止您将静态方法包装在仿函数甚至 lambda 中?
  • @WhozCraig: boost::bind(foo, _1) 将创建函数对象。
  • 你应该添加一些代码,你的函数foo的接口,你要调用的API的接口和错误信息。
  • @merlin 我想过,但那可能是任何结构或类。不确定他是否知道他在说什么。如果函数接受任何可调用的内容,则指向函数的指针与指向函子的指针相同。

标签: c++ boost


【解决方案1】:

除了将自己的仿函数编写为Functor&lt;int, int&gt; 的派生类型之外,您似乎别无选择。但是,您可以通过提供可以从函子或函子指针实例化的中间类模板函子来省去一些麻烦:

template<typename R, typename A>
struct GenericFunctor<R, A> : public Functor<R, A>
{
    template <typename F>
    MyFunctor(F f) : f_(f) {}
    ReturnType operator()(A arg) = { return f_(arg);}
private:
    std::function<R(A)> f_; // or boost::function
};

那你可以说

GenericFunctor<int, int> fun = foo;
API(&fun);  // works. GenericFinctor<int,int> is a Functor<int,int>

这只是一个解决方法,因为你得到的东西太糟糕了。

【讨论】:

  • 感谢您大胆地表示这是不可能的,实现 Functor 是唯一的解决方案。我想知道为什么人们会突然对一个问题进行排名,而它可能有否定的答案,这也很有帮助。
  • @VishnuKanwar 您正在实施Functor。使用继承。
  • 非常感谢 juanchopanza 看起来是一个不错的中间解决方案。
  • 我想请您就这个问题给您的专家 cmet 先生:stackoverflow.com/questions/19269438/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-21
  • 2011-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多