function函数对象类型实现原理
大约 1 分钟
function函数对象类型实现原理
通过两个例子:一个是持有普通函数,一个是持有类成员方法;查看类的成员方法到底是什么。
#include <iostream>
#include <typeinfo>
#include <string>
#include <functional>
using namespace std;
/*
function函数对象类型的实现原理
*/
void hello(string str) { cout << str << endl; }
int sum(int a, int b) { return a + b; }
///
template<typename Fty>
class myfunction {};
#if 0
//模板的部分偏特化
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);//hello(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);//hello(arg)
}
private:
PFUNC _pfunc;
};
#endif
//可变参模板
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...);//hello(arg) 表示一组形参变量
}
private:
PFUNC _pfunc;
};
int main()
{
function<void(string)> func1(hello);
func1("hello world!");//func1.operator()("hello world!")
myfunction<int(int, int)> func2(sum);
cout << func2(10, 20) << endl;
return 0;
}
- 用函数指针保存函数类型
- 由于反返回类型只有一个,函数参数的类型有多种可能或者不确定,如果每个都写出来太麻烦,可以使用可变模板参数代替