我想实现一个类似于 boost::function 的类 Function,类 Function 可以在 main.cpp 中这样使用:
#include <iostream>
#include "Function.hpp"
int funct1(char c)
{
std::cout << c << std::endl;
return 0;
}
int main()
{
Function<int (char)> f = &funct1;
Function<int (char)> b = boost::bind(&funct1, _1);
f('f');
b('b');
return 0;
}
在我的 Function.hpp 中,我有
template <typename T>
class Function;
template <typename T, typename P1>
class Function<T(P1)>
{
typedef int (*ptr)(P1);
public:
Function(int (*n)(P1)) : _o(n)
{
}
int operator()(P1 const& p)
{
return _o(p);
}
Function<T(P1)>& operator=(int (*n)(P1))
{
_o = n;
return *this;
}
private:
ptr _o; // function pointer
};
上面的代码适用于 Function f = &funct1,
但不适用于 Function b = boost::bind(&funct1, _1);
我想知道 boost::Function 究竟是如何工作的,以及我能做些什么来支持我的 Function 支持 boost::bind