模板技术

为什么会有模板技术呢?

在编写功能类似的函数时候,如:double fun(); int fun(); char fun(); 如果fun函数都是处理类似的问题时,那么是不是有一种通用的过程来取代这种要为每种类型定义一次函数的方法?

那么,问题的解决方法就是模板技术。

1、函数模板和类模板

1.1函数模板:[语法]

template <class T1,class T2,....,class Tn>

.....

View Code
 1 #include <iostream>
2 using namespace std;
3 template <class T>
4 T fun(T t1,T t2)
5 {
6 return t1>t2?t1:t2;
7 }
8
9 void main()
10 {
11 cout << fun(1.2,1.4) << endl;
12 }

1.2类模板:[语法]

template <class T1,class T2,....,class Tn>

......

View Code
 1 #include <iostream>
2 using namespace std;
3
4 template <class T>
5 class compare
6 {
7 public:
8 bool IsEqual(const T t1,const T t2)
9 {
10 return t1 == t2;
11 }
12 };
13 void main()
14 {
15 compare<int> c;
16 cout << c.IsEqual(1,1) << endl;
17
18 compare<double> d;
19 cout << d.IsEqual(1.0,1.2) << endl;
20 }


2 、模板特化

当定义了模板后,如果想对某种特定类型执行不一样的过程,那么怎么办呢?[模板还是同以上的]

2.1 函数模板特化

View Code
 1 #include <iostream>
2 using namespace std;
3
4 template <class T> // 函数模板
5 T fun(T t1,T t2)
6 {
7 return t1>t2?t1:t2;
8 }
9
10 template <>
11 int fun(int t1,int t2) //特化
12 {
13 return t1+t2;
14 }
15 void main()
16 {
17 cout << fun(1,1) << endl;
18 }

2.2 类模板特化

View Code
 1 #include <iostream>
2 using namespace std;
3
4 template <class T>
5 class compare
6 {
7 public:
8 bool IsEqual(const T t1,const T t2)
9 {
10 return t1 == t2;
11 }
12 };
13
14 template<>
15 class compare<double>
16 {
17 public:
18 bool IsEqual(const double t1,const double t2)
19 {
20 return (bool)(t1 + t2);
21 }
22 };
23
24 void main()
25 {
26 compare<int> c;
27 cout << c.IsEqual(1,1) << endl;
28
29 compare<double> d;
30 cout << d.IsEqual(1.0,1.2) << endl; // 如果不使用特化技术,这里的返回值应该是0,但是使用了这种技术后,这里的返回值是1
31 }

2.3函数存在特化;类存在特化和偏特化

    template<class Window>                        //仍然使用原来的泛化定义;
    class Widget<Window, MyController>      //MyController是具体的类,是特化定义;
    {
      //... 偏特化实现代码 ...
    };


 ==================================

template的特殊用法:

/*template<class或者typename或者非类型模版参数>
非类型模版参数

一般来说,非类型模板参数可以是常整数(包括枚举)或者指向外部链接对象的指针。
那么就是说,浮点数是不行的,指向内部链接对象的指针是不行的。
*/

template<typename T, int MAXSIZE>
class Stack{
Private:
       T elems[MAXSIZE];
…
};
Int main()
{
       Stack<int, 20> int20Stack;
       Stack<int, 40> int40Stack;
…
};

可以把非类型模板参数,当作类的形参看待,这些形参对于整个类的成员函数都可见。
一般,用于外部数据在调用时传入时使用。

如下:

template<uint32_t SNDBUFSIZE, uint32_t RCVBUFSIZE, uint32_t SNDBUFLEN>
class Tcp
{
public:
   Tcp()
   {    
        std::cout << SNDBUFSIZE << " " << RCVBUFSIZE << " " << SNDBUFLEN << std::endl;
    }
};


class Test : public Tcp<100,100,100>
{
    
};


 

 

posted on 2012-04-02 16:49  笔记吧... 可能只有自己看得懂  阅读(503)  评论(0编辑  收藏  举报