简单版
#include<iostream>
#include<typeinfo>
#include<string>
#include<functional>
using namespace std;
void hello(string str)
{
cout<<str<<endl;
}
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;
};
int main(void)
{
myfunction<void(string)> func1(hello);
func1("hello world");
return 0;
}
具体实现原理
#include<iostream>
#include<typeinfo>
#include<string>
#include<functional>
using namespace std;
void hello(string str,int a)
{
cout<<to_string(a)<<endl;
cout<<str<<endl;
}
template<typename Fty>
class myfunction{};
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(void)
{
myfunction<void(string,int)> func1(hello);
func1("hello world",20);
return 0;
}