C++超基础:类模板——下、类模版的特化

来源:互联网 发布:淘宝坑店 编辑:程序博客网 时间:2024/05/29 18:24

一、类的特化

1、编译器会自动优先选择特化的类模版

2、函数模版和类模版的模版参数也可以是普通数值

#include <iostream>using namespace std;template<typename T1, typename T2>class Test{public:void add(T1 a, T2 b){cout<<"Test"<<endl;cout<<(a + b)<<endl;}};/*template<typename T>class Test<T, T>{public:void add(T a, T b){cout<<"Test<T, T>"<<endl;cout<<static_cast<T>(a + b)<<endl;}};*/template<typename T>class Test<T, int>{public:void add(T a, int b){cout<<"Test<T, int>"<<endl;cout<<(a + b)<<endl;}};template<typename T1, typename T2>class Test<T1 *, T2 *>{public:void add(T1 *a, T2 *b){cout<<"Test<T1 *, T2 *>"<<endl;cout<<"add(T1 *a, T2 *b)"<<endl;}};template<typename T, int N>void func(){T array[N] = {0};for (int i=0; i<N; i++){array[i] = i + 1;cout<<array[i]<<endl;}}int main(){Test<double, int> t1;  //选择add(T a, int b)Test<long, long> t2;   //选择add(T a, T b)Test<float, int> t3; //选择add(T a, int b)Test<int*, int*> t4; //选择add(T1 *a, T2 *b)int i = 0;int j = 0;t1.add(10.0001, 8);t2.add(2, 4);t3.add(5,7);t4.add(&i, &j);func<int, 5>();func<float, 5>();return 0;}

二、加法计算

1、加法计算的最快方式,就是在编译的时候计算好,运行时无任何时间开销

2、模版参数不能是变量

3、浮点数和类对象不能作为模版参数

4、全局指针不能作为模版参数

NOTE:递归的时候,编译器的推导过程是在编译阶段完成的。因此,编译器的推导必须依赖于特化类,否则推导过程无法结束。

#include <iostream>using namespace std;template<int N>class Sum{public:static const int VALUE = Sum<N - 1>::VALUE + N;};template<>class Sum<1>{public:static const int VALUE = 1;};int main(){cout<<Sum<10>::VALUE<<endl;cout<<Sum<100>::VALUE<<endl;return 0;}

三、工程问题

1、实际工程中内存操作是BUG的重要来源

2、C++把堆内存交由程序员来自由使用。因此,当未及时释放,会产生内存泄漏、重复释放内存2次、使用越界会产生问题。所以,怎么样最大限度的避免上述问题尼?

解决办法:

1、开发一个数组类来代替C的原生数组,操作符重载的时候检查是否越界,如果越界马上退出

2、用智能指针来代替C的原生指针,最大限度的避免内存泄漏很多次释放内存的问题,什么是“智能指针”?,例子分析:



/*SmartPointer.h*/#ifndef _SMARTPOINTER_H_#define _SMARTPOINTER_H_template<typename T>class SmartPoint{protected:T *m_pointer;public:SmartPoint();~SmartPoint();SmartPoint(const T *point);T *operator->();T &operator*();};#endif

/*SmartPointer.hpp*/#ifndef _SMARTPOINTER_DEF_H_#define _SMARTPOINTER_DEF_H_#include "SmartPointer.h"template<typename T>SmartPoint<T>::SmartPoint(){m_pointer = NULL;}template<typename T>SmartPoint<T>::SmartPoint(const T* point){m_pointer = const_cast<T*>(point);}template<typename T>SmartPoint<T>::~SmartPoint(){delete m_pointer;}template<typename T>T *SmartPoint<T>::operator->(){return m_pointer;}template<typename T>T &SmartPoint<T>::operator*(){return *m_pointer;}#endif

/*test.cpp*/#include <iostream>#include "SmartPointer.hpp"using namespace std;class Test{public:int i;void print(){cout<<i<<endl;}};int main(){SmartPoint<int> p = new int(5);cout<<*p<<endl;*p = 3;cout<<*p<<endl;SmartPoint<Test> q = new Test();q->i = 10;//q.operator->()->i = 10;q->print();return 0;}



0 0
原创粉丝点击