实现STL的function迷你版
char buffer[1024] = { 0 };
template<typename Functor, typename R, typename... A>
struct Invoker
{
static R invoke(A... args)
{
Functor* p = (Functor*)buffer;
return (*p)(args...);
}
};
template<typename Fty>
class myfunction {};
template<typename R, typename... A>
class myfunction<R(A...)> {
public:
typedef R(*PFUNC)(A...);
template<typename Functor>
myfunction(Functor func)
{
new (buffer) Functor(func);
_pfunc = &Invoker<Functor, R, A...>::invoke;
};
R operator()(A... arg) {
return _pfunc(arg...);
}
private:
PFUNC _pfunc;
};
void hello1(int data)
{
cout << data << endl;
}
void hello2(int data, string str)
{
cout << data << endl;
cout << str << endl;
}
int main()
{
myfunction<void()> f1 = bind(hello1, 1);
f1();
myfunction<void(string)> f2 = bind(hello2, 1, placeholders::_1);
f2("hello world");
}