- Hands-On Embedded Programming with C++17
- Maya Posch
- 219字
- 2021-08-20 10:20:47
Templates
It's often thought that templates in C++ are very heavy, and carry a severe penalty for using them. This completely misses the point of templates, which is that templates are merely meant to be used as a shorthand method for automating the generation of nearly identical code from a single template – hence the name.
What this effectively means is that for any function or class template we define, the compiler will generate an inline implementation of the template each time the template is referenced.
This is a pattern we commonly see in the C++ standard template library (STL), which, as the name suggests, makes heavy use of templates. Take, for example, a data structure like a humble map:
std::map<std::string, int> myMap;
What happens here is that the singular template for an std::map is taken by the compiler, along with the template parameters we provide within the sharp brackets, filling in the template and writing an inline implementation in its spot.
Effectively, we get the same implementation as if we had written the entire data structure implementation by hand just for those two types. Since the alternative would be to write every implementation by hand for every conceivable built-in type and additional user-defined type, the use of a generic template saves us a lot of time, without sacrificing performance.
- 新媒體跨界交互設(shè)計(jì)
- Cortex-M3 + μC/OS-II嵌入式系統(tǒng)開(kāi)發(fā)入門(mén)與應(yīng)用
- OUYA Game Development by Example
- Rapid BeagleBoard Prototyping with MATLAB and Simulink
- SiFive 經(jīng)典RISC-V FE310微控制器原理與實(shí)踐
- Intel FPGA權(quán)威設(shè)計(jì)指南:基于Quartus Prime Pro 19集成開(kāi)發(fā)環(huán)境
- IP網(wǎng)絡(luò)視頻傳輸:技術(shù)、標(biāo)準(zhǔn)和應(yīng)用
- 計(jì)算機(jī)組裝與維護(hù)(慕課版)
- 計(jì)算機(jī)組成技術(shù)教程
- UML精粹:標(biāo)準(zhǔn)對(duì)象建模語(yǔ)言簡(jiǎn)明指南(第3版)
- Exceptional C++:47個(gè)C++工程難題、編程問(wèn)題和解決方案(中文版)
- 新編計(jì)算機(jī)組裝與維護(hù)
- Mastering Unity 2D Game Development
- 電腦組裝與硬件維修入門(mén)與提高
- Hands-On Python Deep Learning for the Web