模板初步

 最近看Thinking in c++ vol2感觉获益不少,今天看到STL感觉还是蛮震撼的,短短的几句话,简单的模版就解决了问题

先看个例子:

 
#include <cstdlib>
#include <functional>
#include <iostream>
#include <string>
using namespace std;

template<typename R, typename E, typename Func1, typename Func2>
class unary_composer {
 Func1 f1;
 Func2 f2;
public:
 unary_composer(Func1 fone,Func2 ftwo) : f1(fone),f2(ftwo) {}
 R operator()(E x) { return f1(f2(x)); }
};

template<typename R, typename E, typename Func1, typename Func2>
unary_composer<R,E,Func1,Func2> comp(Func1 f1,Func2 f2) {
 return unary_composer<R,E,Func1,Func2>(f1,f2);
}
int main()
{
 double x = comp<double,const string&>(
  atof, mem_fun_ref(&string::c_str))("12.34");
 cout << x << endl;
 
 return 0;
}
 
看完了这个,不由暗暗佩服,利用模版参数的推衍只需要提供2个参数就搞定了,1个是返回值类型参数,1个是函数的参数的类型,重载了()使得其调用相当于
atof(string("12.34").cstr())
真的很爽
不过还有更爽的,只要直接从unary_function派生个类,然后利用ptr_fun把函数指针搞成函数对象现在连一个模版参数都不用给了~~
#include <cstdlib>
#include <functional>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
template<typename Func1, typename Func2> class unary_composer
: public unary_function<typename Func2::argument_type,
      typename Func1::result_type> {
 Func1 f1;
 Func2 f2; 
public:
 unary_composer(Func1 fone,Func2 ftwo):f1(fone),f2(ftwo) {}
 typename Func1::result_type
  operator()(typename Func2::argument_type x) { return f1(f2(x)); }
};

template<typename Func1, typename Func2>
unary_composer<Func1,Func2> comp(Func1 f1, Func2 f2) {
 return unary_composer<Func1,Func2>(f1,f2);
}
int main() {
 vector<double> vd;
 vector<string> vs;
 vs.push_back("1.1");
 vs.push_back("1.2");
 transform(vs.begin(),vs.end(),back_inserter(vd),
  comp(ptr_fun(atof),mem_fun_ref(&string::c_str)));
 
 for(vector<double>::iterator it = vd.begin(); it != vd.end(); ++it)
  cout << *it << endl;
 
 return 0;
}
 
模版,STL,神奇的东西~~
顺便B4一下微软的STL,不看MSDN不知道参数都是干啥的~
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值