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++(中文版)
型别推导
21
数组实参
以上已经基本讨论完模板型别推导的主流情况,但还有一个边缘情况值得了解。这种
情况是:数组型别有别于指针型别,尽管有时它们看起来可以互换。形成这种假象的
主要原因是,在很多语境下,数组会退化成指涉到其首元素的指针。下面这段代码之
所以能够通过编译,就是因为这种退化机制在发挥作用:
const char name[] = "J. P. Briggs";
// name
的型别是
const char[13]
const char * ptrToName = name;
//
数组退化成指针
这里,型别为
const char *
的指针
ptrToName
是通过
name
来初始化的,而后者的型
别是
const char[13]
。这两个型别(
const char *
const char[13]
)并不统一,
但是因为数组到指针的退化规则地存在,上述代码能够通过编译。
但当一个数组传递给持有按值形参的模板时,又会怎样呢?
template<typename T>
void f(T param);
//
持有按值形参的模板
f(name);
// T
param
的型别会被推导成什么呢?
我们先是观察到,并没有任何的函数形参具有数组型别。没错,下面的语法是合法的:
void myFunc(int param
[]
);
但是既然数组声明可以按照指针声明方式加以处理,那就意味着
myFunc
可以等价地
声明如下:
void myFunc(int
*
param);
这种数组和指针形参的等价性,是作为 ...
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
Go语言编程

Go语言编程

威廉·肯尼迪

Publisher Resources

ISBN: 9787519817749