模板的特化
模板特化是C++模板编程中极其重要机制,模板特化就是模板编译时多态实现。
特化版本和普通版本拥有不同的外部接口和实现
偏特化:对部分模板参数进行特化。
支持普通版本,特化版本,偏特化版本
//template_special_vectorbool.cpp
vector对bool的特化处理,和别的细节差别
普通特化
#include <iostream>
using namespace std;
template <typename T>
class Array {
private:
T* ptr;
int size;
public:
Array(T arr[], int s);
void print();
};
template <typename T>
Array<T>::Array(T arr[], int s)
{
ptr = new T[s];
size = s;
for (int i = 0; i < size; i++)
ptr[i] = arr[i];
}
template <typename T>
void Array<T>::print()
{
for (int i = 0; i < size; i++)
cout << *(ptr + i)<<" ";
cout << endl;
}
template<>
void Array<bool>::print()
{
for (int i = 0; i < size; i++)
cout << *(ptr + i);
cout << endl;
}
int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
Array<int> a1(arr, 5);
a1.print();
bool boo[5] = { true, false, true, false, true };
Array<bool> a2(boo, 5);
a2.print();
}
kongcb@tcu-pc:~/testcode/template$ g++ template_special.cpp -o template_special
kongcb@tcu-pc:~/testcode/template$ ./template_special
1 2 3 4 5
10101
偏特化
#include <iostream>
#include <memory>
using namespace std;
template <typename U, typename V>
struct Printer{
U x;
V y;
void print()
{
cout<<x<<","<<y<<endl;
}
};
template <>
struct Printer<int,int>{
int x;
int y;
void print()
{
cout<<"["<<x<<","<<y<<"]"<<endl;
}
};
template <>
struct Printer<double,double>{
double x;
double y;
void print()
{
cout<<"{"<<x<<","<<y<<"}"<<endl;
}
};
template <typename V>
struct Printer<int,V>{
int x;
V y;
void print()
{
cout<<"["<<x<<"] "<<y<<endl;
}
};
template <typename U, typename V>
struct Printer<U*, V*> {
U* x;
V* y;
void print()
{
cout<<x<<"->"<<*x<<endl;
cout<<y<<"->"<<*y<<endl;
}
};
int main()
{
Printer<string, string> p1{"C++", "Java"};
p1.print();
Printer<int, int> p2{100,200};
p2.print();
Printer<double, double> p3{10.2,20.3};
p3.print();
Printer<int, string> p4{100,"C++"};
p4.print();
auto i1=make_unique<int>(100);
auto i2=make_unique<int>(200);
Printer<int*, int*> p5{i1.get(),i2.get()};
p5.print();
}
kongcb@tcu-pc:~/testcode/template$ g++ template_special_part.cpp -o template_special_part
kongcb@tcu-pc:~/testcode/template$ ./template_special_part
C++,Java
[100,200]
{10.2,20.3}
[100] C++
0x229e030->100
0x229e050->200
vector对bool特殊特化
#include <vector>
#include <iostream>
using namespace std;
void zero(auto& container){
for(auto&& val: container){
val={};
}
}
void print(auto& container){
for(auto&& val: container){
cout<<val<<" ";
}
cout<<endl;
}
int main()
{
vector<int> vc={1,2,3};
print(vc);
zero(vc);
print(vc);
int& c=vc[0];
vector<bool> vb={true,false,true};
print(vb);
zero(vb);
print(vb);
}
kongcb@tcu-pc:~/testcode/template$ g++ template_special_vectorbool.cpp -o template_special_vectorbool -fconcepts-ts
kongcb@tcu-pc:~/testcode/template$ ./template_special_vectorbool
1 2 3
0 0 0
1 0 1
0 0 0