auto cbegin(const C& container)->decltype(std::begin(container))
{
return std::begin(container);
//
请仔细看下文的解释
}
当你看到非成员函数版本的
cbegin
并没有调用成员函数版本的
cbegin
时,是不是
吃了一惊?我其实刚看到时也吓一跳。但顺着逻辑推导一下。这个
cbegin
模板接
受一个形参
C
,实参型别可以是任何表示类似容器的数据结构,并通过其引用到
const
型别的形参
container
来
访问该实参。如果
C
对应一个传统容器型别(例如,
std::vector<int>
),则
container
就是该容器型别的引用到
const
的版本(例如,
const std::vector<int>&
)。调用(
C++11
提供的)非成员函数版本的
begin
函数
并传入一个
const
容器会产生一个
const_iterator
,而模板返回的正是这个迭代器。
这样实现的好处是它对于那些只提供了
begin
成员函数(
C++11
的非成员函数版本的
begin
调用的就是它)而未提供
cbegin
成员函数的容器也适用。这么一来,你就可以
把这个非成员函数版本的
cbegin
用在那些仅直接支持
begin
的容器上了。
该模板在
C
是一个内建数组时也适用。在这种情况下, ...
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.
O’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
I 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
I’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
I'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.