Skip to Content
Effective Modern C++(中文版)
book

Effective Modern C++(中文版)

by Scott Meyers
April 2018
Intermediate to advanced
303 pages
4h 54m
Chinese
China Electric Power Press Ltd.
Content preview from Effective Modern C++(中文版)
22
1
然后,向其传递一个数组,
f(name);
//
f
传递一个数组
在这种情况下,
T
的型别会被推导成实际的数组型别!这个型别中会包含数组尺寸,在
本例中,
T
的型别推导结果是
const char [13]
,而
f
的形参(该数组的一个引用)型
别则被推导为
const char (&)[13]
。没错,语法看起来又臭又长,但了解到这个程度
却会让你在面对极少数较真的人时,挣得好大一个面子。
有意思的是,可以利用声明数组引用这一能力创造出一个模板,用来推导出数组含有
的元素个数:
//
以编译期常量形式返回数组尺寸
//
(该数组形参未起名字,因为我们只关心其含有的元素个数)
template<typename T, std::size_t N>
//
关于
constexpr
constexpr std::size_t arraySize(T (&)[N]) noexcept
//
noexcept
{
//
的说明,
return
N
;
//
请参考下文
}
条款
15
所释,将该函数声明为
constexpr
,能够使得其返回值在编译期就可用。从
而就可以在声明一个数组时,指定其尺寸和另一数组相同,而后者的尺寸则从花括号
初始化式(
braced initializer
)计算得出:
int keyVals[] = { 1, 3, 7, 9, 11, 22, 35 };
// keyVals
含有
7
个元素
int mappedVals[
arraySize(keyVals) ...
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

流畅的Python(第2版)

流畅的Python(第2版)

Luciano Ramalho
Effective STL

Effective STL

Scott Meyers

Publisher Resources

ISBN: 9787519817749