《MCD》仿函数学习笔记,欢迎讨论
oopig 2003-12-10 10:54:21
主要结构:
一、对一些要点,根据自己的理解做出说明
二、实做出自己的一份简单实现
三、提出一些问题
调试环境:
fedora core 1.0
Kdevelop2.1.5/g++ 3.3.2
今天先说说我理解的一些技术要点:
一、MCD仿函数的技术要点
1. 偏特化是基础,一定要掌握好
这个不用多说了,要学习mcd functor,偏特化一定要理解好,比如以下代码必须达到可以随手拈来的程度:
#include <iostream>
using namespace std;
template <typename T>
struct Refrence
{
enum { is_refrence = false };
};
template <typename T>
struct Refrence<T&>
{
enum { is_refrence = true };
};
template <typename T>
struct Refrence<const T&>
{
enum { is_refrence = true };
};
int main()
{
cout << Refrence<int>::is_refrence << endl; //output: 1
cout << Refrence<int&>::is_refrence << endl; //output: 1
cout << Refrence<const int&>::is_refrence << endl; //output: 0
return 0;
}
2.Functor的模版构造函数
要理解Functor模版构造函数的作用就是可以接受任意型别,说是任意型别,但是这里只使用于各种“函数”,包括普通函数,仿函数、成员函数等。
这一点很重要,因为MCD的仿函数能够海纳百川,通吃各种“函数”,靠的就是这一手。
再用些代码来说明:
#include <iostream>
using namespace std;
void foo1()
{ cout << "void foo1()" << endl; }
void foo2()
{ cout << "char foo2()" << endl; }
struct Function
{
template <typename Fun>
Function(const Fun &fun) //可以接收任意返回值的无显式参数的“函数”
{ fun(); }
};
int main()
{
Function fun1(static_cast<void(*)()>(foo1)); //output: void foo1()
Function fun2(static_cast<char(*)()>(foo2)); //output: char foo2()
return 0;
}
待续。。。