当前位置:网站首页>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
边栏推荐
- 蓝天NH55系列笔记本内存读写速度奇慢解决过程记录
- How to apply for PMP project management certification examination?
- 可观测|时序数据降采样在Prometheus实践复盘
- Is the account opening link of Huatai Securities with low commission safe?
- 华泰证券低佣金的开户链接安全吗?
- Application of machine learning in housing price prediction
- MySQL数据库备份与恢复--mysqldump命令
- The difference between cout/cerr/clog
- 股票账户佣金怎么调低,炒股佣金怎么调低网上开户安全吗
- 如何有效对直流列头柜进行监测
猜你喜欢

phpcms付费阅读功能支付宝支付

MariaDB's Galera cluster application scenario -- multi master and multi active databases

高配笔记本使用CAD搬砖时卡死解决记录

In the enterprise, win10 turns on BitLocker to lock the disk, how to back up the system, how to recover when the system has problems, and how to recover quickly while taking into account system securi

Blue sky nh55 series notebook memory reading and writing speed is extremely slow, solution process record

How to do the project of computer remote company in foreign Internet?

45岁教授,她投出2个超级独角兽

Selected cutting-edge technical articles of Bi Ren Academy of science and technology
![[JS] - [sort related] - Notes](/img/b7/af467c7a169b73c3c4936072aef8b9.png)
[JS] - [sort related] - Notes

法国学者:最优传输理论下对抗攻击可解释性探讨
随机推荐
机器人强化学习——Learning Synergies between Pushing and Grasping with Self-supervised DRL (2018)
如何有效对直流列头柜进行监测
[binary tree] the maximum difference between a node and its ancestor
【js】-【动态规划】-笔记
【爬虫】数据提取之JSONpath
Réseau graphique: Qu'est - ce que le Protocole d'équilibrage de charge de passerelle glbp?
The difference between debug and release
Question brushing guide public
[Peking University] tensorflow2.0-1-opening
MariaDB的Galera集群应用场景--数据库多主多活
Stm32 Reverse Introduction to CTF Competition Interpretation
模板的进阶
企业里Win10 开启BitLocker锁定磁盘,如何备份系统,当系统出现问题又如何恢复,快速恢复又兼顾系统安全(远程设备篇)
Application of machine learning in housing price prediction
城市轨道交通站应急照明疏散指示系统设计
Solution record of jamming when using CAD to move bricks in high configuration notebook
端口映射和端口转发区别是什么
Recommended collection: build a cross cloud data warehouse environment, which is particularly dry!
The initial arrangement of particles in SPH (solved by two pictures)
取得PMP證書需要多長時間?