最近几天都在看模板,它真的可以算是C++中最复杂的部分了。昨天和今天又看了一下TR1中functional的部分,发现其中的bind真可谓是无比强大。源代码还没有完全看完,不过已经忍不住自己模拟着写了一个,与TR1中的bind相比,缺少了占位符的功能,虽说这样一来彪悍程度大打折扣,不过花了这两个多小时实现了bind的其它部分,还是有些成就感的,哈哈,自己发文YY一下
- #include <iostream>
- using namespace std;
- template <typename Signature>
- class BindZ;
- template <typename Signature>
- class result_ofZ;
- template <typename Signature>
- class get_raw_typeZ;
- template <typename R, typename T>
- class result_ofZ<R (T)>
- {
- public:
- typedef R type;
- };
- template <typename T>
- class get_raw_typeZ<T*>
- {
- public:
- typedef T raw_type;
- };
- template <typename F, typename T>
- class BindZ<F (T)>
- {
- public:
- BindZ(F f, T a) : m_fun(f), m_arg(a)
- {
- }
- typename result_ofZ<typename get_raw_typeZ<F>::raw_type>::type operator ()()
- {
- return m_fun(m_arg);
- }
- private:
- F m_fun;
- T m_arg;
- };
- template <typename F, typename T>
- BindZ<F (T)> bindZ(F f, T a)
- {
- return BindZ<F (T)>(f, a);
- }
- int foo(int a)
- {
- cout << a << endl;
- return 0;
- }
- int main()
- {
- cout << typeid(bindZ(foo, 1)()).name() << endl;
- return 0;
- }