//从funcion 到function 模板
/*
function 函数对象类型的实现原理
*/
#include <iostream>
using namespace std;
void hello(string str1, string str2){
cout<<str1<<"\n"<<str2<<endl;
}
//注意需要在这里进行声明,先申明再定义,再通过对象调用
template<typename Fty>
class myfunction{};
//R 函数返回类型
//A1函数形参1
//A2函数形参2
template<typename R, typename A1, typename A2>
class myfunction<R(A1, A2)>{
public:
using PFUNC = R(*)(A1, A2); //定义函数指针对象类型
myfunction(PFUNC func) : _pfunc(func){};
//构造函数 重载 myfunction<void(string, string)> fuc02(hello);
R operator()(A1 arg1, A2 arg2){
return _pfunc(arg1, arg2);
}
private:
PFUNC _pfunc;
};
int main(){
// function<void(string)> fuc01(hello);
// fuc01("hello world, my name is zhangbuda...\nyour name is ?");
myfunction<void(string, string)> fuc02(hello);
fuc02("hello world.......\nmy name is zhangbuda", "how are you?");
return 0;
}
//形参可变的情况
//可变形参 参数不确定
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;
};
c++ | funtion
于 2023-08-07 23:16:30 首次发布