void hello(string str)
{
cout << str << endl;
}
int sum(int a,int b)
{
return a+b;
}
template<typename FTy>
class myfunction
{};
template<typename R,typename A1>
class myfunction<R(A1)>
{
public:
using PFUNC = R(*)(A1);
myfunction(PFUNC pfunc):_pfunc(pfunc)
{}
R operator()(A1 arg)
{
return _pfunc(arg);
}
private:
PFUNC _pfunc;
};
template<typename R,typename A1,typename A2>
class myfunction<R(A1,A2)>
{
public:
using PFUNC = R(*)(A1,A2);
myfunction(PFUNC pfunc):_pfunc(pfunc)
{}
R operator()(A1 arg1,A2 arg2)
{
return _pfunc(arg1,arg2);
}
private:
PFUNC _pfunc;
};
//以下为最终版本:
template<typename R,typename...A>
class myfunction<R(A...)>
{
public:
using PFUNC = R(*)(A...);
myfunction(PFUNC pfunc):_pfunc(pfunc){}
R operator()(A... arg)
{
return _pfunc(arg...);
}
private:
PFUNC _pfunc;
};
int main()
{
myfunction<void(string)> func1(hello);
func1("hello world!");//func1.operator()("hello world!")
myfuncion<int(int,int)> func2(sum);
cout << func2(10,20) << endl;
}
36. function实现原理
最新推荐文章于 2022-12-15 20:29:38 发布