当前位置:网站首页>Advanced template
Advanced template
2022-07-04 23:38:00 【Xifeng】
Catalog
Advanced of template
Non type template parameters
// Non type template parameters -- Must be an integer constant
template<class T,size_t N=100>
struct Stack
{
// If you just want to define a static stack , You can use this method
private:
T _st[N];
size_t _top;
};
Template specialization
Concept
Usually , Using templates, you can implement some type independent code , But for some special types, you may get some wrong results , Just The template needs to be specialized . namely : Based on the original template class , Implementation of specialization for special types . Template specialization is divided into Function template specialization And Class template specialization
Specialization of function templates
Specialization steps of function template :
- You must first have a basic function template
- keyword template Followed by a pair of empty angle brackets <>
- The function name is followed by a pair of angle brackets , Specify the type to be specialized in angle brackets
- Function parameter table : Must be exactly the same as the base parameter type of the template function , If different compilers may report some strange errors .
// Specialization of function templates
// This is normal function template matching
template <class T>
bool Objless(T d1 , T d2) //1
{
return d1 < d2;
}
bool Objless( yyr::Date*& p1, yyr::Date*& p2) //2
{
return *p1 < *p2;
}
// This method is the specialization of function templates
template<>
bool Objless<yyr::Date*>(yyr::Date* p1, yyr::Date* p2)//3
{
return *p1 < *p2;
}
// The specialization of function templates is relatively weak , In practical application, it is completely possible to overload a Date* Is a function of parameters ,2 and 3 Can exist at the same time , And the compiler will automatically call 2
void fun3()
{
// It is inevitable to encounter such problems in the process of use , Take the date class as an example
cout << Objless(1, 2) << endl;// There is no problem with that
yyr::Date* d1 = new yyr::Date(2022, 3, 20);
yyr::Date* d2 = new yyr::Date(2022, 5, 30);
cout << Objless(d1, d2) << endl;// without 2, There is something wrong with running , He compared the pointer
}
Be careful : In general, if the function template encounters a type that cannot be processed or is processed incorrectly , In order to achieve simplicity, the function is usually given directly .
class template specialization
Full specialization
Full specialization is to determine all parameters in the template parameter list , Non type template parameters can also be specialized .
// Classic scenario of class template specialization :
template<class T>
struct Less
{
bool operator()(const T& x.const T& y) const
{
return x < y;
}
};
// When it's a date class , You can't simply compare , Instead, you need to dereference and then compare
template<>
struct Less<Date*>
{
bool operator()(const Date*& d1, const Date*& d2) const
{
return *d1 < *d2;
}
};
Partial specialization
Partial specialization : Any specialized version of further conditional design for template parameters .
template<class T1,class T2>
class date // Define a class template
{
public:
date()
{
cout << typeid(T1).name() << "----";
cout << typeid(T2).name() << endl;
}
};
// Full specialization
template<>
class date<int, char>
{
public:
date()
{
cout << "int,char" << endl;
}
};
// The following are partial specialization
template<class T1,class T2>
class date<T1*, T2*>
{
public:
date()
{
cout << "T1*, T2*" << endl;
}
};
template<class T>
class date<T, char>
{
public:
date()
{
cout << "T,char" << endl;
}
};
template<class T1, class T2>
class date<T1&, T2&>
{
public:
date()
{
cout << "T1&, T2&" << endl;
}
};
void fun1()
{
// Observe which of the above templates is used by the following functions
date<int, int> d1;
date<int, char> d2;
date<int*, double*> d3;
date<double, char> d4;
date<int&, double&> d5;
}
Separate compilation of templates
In the header file pragma once, It can prevent repeated expansion .
What is separate compilation
A program ( project ) It is realized by several source files , Each source file is compiled separately to generate the target file , Finally, chain all the target files
The process of forming a single executable file is called separate compilation mode .
advantage : The advantage of the separation of declaration and definition is that it is easy to maintain , see .h Understand the basic functions of framework design , see .cpp Understand the specific implementation details .
Separate compilation of templates ( There is a link problem , Not a declaration issue )
First, the compiler does not support separate compilation of templates , There are two solutions
// Suppose the following is a function implementation cpp file , The statement in .h In file
template<class T>
void funA(const T& A)
{
cout << "funA() " << A << endl;
}
//1. Explicit Instantiation
// But this is weird , I feel like I have lost the meaning of generics , Because you need to instantiate everything in advance
template
void funA<int>(const int& A);
//2、 Definition and declaration are not separated ( recommend )
// Where to use it , After the header file is expanded, there is the definition and instantiation of the template , You can get the address directly , There is no need to link
// This is the use of funA Functional cpp file
int main()
{
funA<int>(20);// If the instantiation is not shown, the compilation fails
}
Template summary
【 advantage 】
- Templates reuse code , Save resources , Faster iterative development ,**C++ Standard template library of (STL)** Therefore
- Enhanced code flexibility
【 shortcoming 】
Templates can cause code bloat problems , It will also lead to longer compilation time ( But this is inevitable , We need to write our own code to the compiler to write )
When a template compilation error occurs , The error message is very messy , Not easy to locate errors
边栏推荐
猜你喜欢
【js】-【排序-相关】-笔记
快解析——好用的内网安全软件
CTF競賽題解之stm32逆向入門
ICML 2022 | 3dlinker: e (3) equal variation self encoder for molecular link design
Phpcms paid reading function Alipay payment
Network namespace
Intelligence test to see idioms guess ancient poems wechat applet source code
微服务(Microservice)那点事儿
如何有效对直流列头柜进行监测
[kotlin] the third day
随机推荐
The initial trial is the cross device model upgrade version of Ruijie switch (taking rg-s2952g-e as an example)
蓝天NH55系列笔记本内存读写速度奇慢解决过程记录
认识ThreadPoolExecutor
Selected cutting-edge technical articles of Bi Ren Academy of science and technology
【js】-【排序-相关】-笔记
快解析内网穿透帮助企业快速实现协同办公
S32 design studio for arm 2.2 quick start
Recommended collection: build a cross cloud data warehouse environment, which is particularly dry!
Advantages of Alibaba cloud international CDN
MP advanced operation: time operation, SQL, querywapper, lambdaquerywapper (condition constructor) quick filter enumeration class
Face recognition 5- insight face padding code practice notes
【雅思阅读】王希伟阅读P4(matching2段落信息配对题【困难】)
The initial arrangement of particles in SPH (solved by two pictures)
Cross domain request
MySQL数据库备份与恢复--mysqldump命令
Meet ThreadPoolExecutor
Instructions for go defer
解决无法通过ssh服务远程连接虚拟机
Mysql database backup and recovery -- mysqldump command
Jar batch management gadget