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++(中文版)
右值引用
移动语义和完美转发
197
转发函数,天然就应该是泛型的。
fwd
模板就是个例子,它接受任意型别的实参,然
后无论接受了什么都加以转发。对于这样的泛型,一种符合逻辑的拓展就是使得转发
函数不只是模板,而且是可变长形参模板,从而能够接受任意数量的实参,可变长形
参形式的
fwd
长成这样:
template<typename
...
Ts>
void fwd(Ts&&
...
params)
//
接受任意实参
{
f(std::forward<Ts>(params)
...
);
//
转发所有实参到
f
}
这种形式你可以在很多地方见到,包括标准容器的置入函数(参见条款
42
),以及智
能指针的工厂函数
std::make_shared
std::make_unique
(参见条款
21
)。
给定目标函数
f
和转发函数
fwd
,当以某特定实参调用
f
会执行某操作,而用同一实参
调用
fwd
执行不同的操作,则称完美转发失败:
f( expression );
//
如果本语句执行了某操作,
fwd( expression );
//
而本语句执行了不同的操作,
//
则称
fwd
完美转发
expression
f
失败
有若干种实参会导致该失败。重要之处在于知道这几种实参是什么,以及如何绕过它
们。现在就让我们开始逐一讲述这些不能实施完美转发的实参吧。
大括号初始化物
假设
f
明如下:
void f(const std::vector<int>& v);
在此情况下,以大括号初始化物调用
f
可以通过编译: ...
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版)

本贾尼 斯特劳斯特鲁普
C++语言导学(原书第2版)

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

本贾尼 斯特劳斯特鲁普
Go语言编程

Go语言编程

威廉·肯尼迪

Publisher Resources

ISBN: 9787519817749