Skip to Content
C++程序设计:原理与实践(基础篇)(原书第2版)
book

C++程序设计:原理与实践(基础篇)(原书第2版)

by 本贾尼 斯特劳斯特鲁普
August 2021
Intermediate to advanced
450 pages
9h 36m
Chinese
Pearson
Content preview from C++程序设计:原理与实践(基础篇)(原书第2版)

14.3.5 整数作为模板参数

显然,用类型来参数化类是很有用的。那么,用“其他东西”(如整型值或字符串值)来参数化类又会怎样呢?本质上,任何类别的实参都是有用的,但我们只考虑类型和整数作为参数。其他类别的参数并不像这两种参数那么有用,并且在C++中使用其他类别的参数需要掌握一些非常细节的语言特性。

下面我们讨论一个例子,这是整型值作为模板实参的最常见的用途——一个容器所包含的元素数在编译时就已确定:

我们可以像下面这样使用array(参见15.7节):

显然,array是很简单的——比vector更简单,功能也更有限——那么人们为什么还要使用array而不是vector呢?一种答案是“效率”。我们在编译时就已经知道array的大小,因此编译器可以(为全局对象如gb)分配静态内存和(为局部变量如loc)分配栈内存而不是在自由存储空间中分配内存。当我们进行范围检查时,可直接与常量(大小参数N)进行比较。对于大多数程序而言,效率的提高并不那么显著,但如果你编写的是一个关键的系统组件,例如网络驱动,即使很小的性能提升也很重要。更重要的是,有些程序可能不允许使用自由空间。这类程序通常是嵌入式系统程序和/或安全攸关的程序(参见第25章)。在这类程序中,array比vector更具有优势,因为不会违反临界限制(不使用自由空间)。 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

C++语言导学(原书第2版)

C++语言导学(原书第2版)

本贾尼 斯特劳斯特鲁普
管理Kubernetes

管理Kubernetes

Brendan Burns, Craig Tracey
Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano

Publisher Resources

ISBN: 9787111562252