【发布时间】: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 中生成函数对象,然后是否有办法从函数对象中生成所需的函子?
【问题讨论】:
-
@texasbruce,我想他的意思是stackoverflow.com/questions/356950/c-functors-and-their-uses
-
boost::bind会提供什么方面的帮助吗?是否有什么东西阻止您将静态方法包装在仿函数甚至 lambda 中? -
@WhozCraig: boost::bind(foo, _1) 将创建函数对象。
-
你应该添加一些代码,你的函数foo的接口,你要调用的API的接口和错误信息。
-
@merlin 我想过,但那可能是任何结构或类。不确定他是否知道他在说什么。如果函数接受任何可调用的内容,则指向函数的指针与指向函子的指针相同。