最近看Thinking in c++ vol2感觉获益不少,今天看到STL感觉还是蛮震撼的,短短的几句话,简单的模版就解决了问题
先看个例子:
#include <cstdlib>
#include <functional>
#include <iostream>
#include <string>
using namespace std;
#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);
}
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");
{
double x = comp<double,const string&>(
atof, mem_fun_ref(&string::c_str))("12.34");
cout << x << endl;
return 0;
}
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;
#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)); }
};
: 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;
}
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不知道参数都是干啥的~