2015-04-07 93 views
7

cppreference顯示了這個簽名std::cbegin爲什麼的std :: CBEGIN返回相同類型的std ::開始

template< class C > 
constexpr auto cbegin(const C& c) -> decltype(std::begin(c)); 

難道不應該返回類似C::const_iterator呢?

+0

我同意這個頁面可能會更清晰一點,不會讓人對它做出推理(就像給出的答案中所做的那樣)。另外,爲什麼引入cbegin(以保證常量而不僅僅依賴於參數的常量)可能會有所幫助。 – stefaanv

回答

12

cconst參考,所以std::begin(c)它將返回的C::begin()回報無論const超載。對於標準庫類型,這是一個const_iterator。對於數組類型,它是指向const的指針。

請注意,這依賴於定義C,其他非標準庫用戶與一const過載C::begin()返回一個迭代器,讓您const進入容器中的元素三立執行。

2

CBEGIN實現象下面這樣:

template <class C> 
auto cbegin(const C& container)->decltype(std::begin(container)) 
{ 
    return std::begin(container); // see explanation below 
} 

對應開始如下所示。

template< class C > 
auto begin(C& c) -> decltype(c.begin()); //calling container's begin 

這CBEGIN模板接受任何類型的參數 表示容器狀的數據結構,C,以及它通過其參考給const參數,容器訪問這一論點 。如果C是常規容器 類型(例如,std :: vector),則容器將是對該容器的const 版本的引用(例如,const std :: vector &)。在const容器上調用nonmember begin函數(由C++ 11提供)會產生一個 const_iterator,並且該迭代器就是該模板返回的內容。

例如,如果我已經使用vector作爲參數cbegin像下面一樣。

std::vector<int> v1; 
std::cbegin(v1); 

現在,看看如何演繹模板在這種情況下發生的,模板(C類)被推斷爲推斷爲const vector<int> &載體和cbegin(常量ç&容器)的參數。現在因爲容器本身是恆定的,它將返回矢量開始的恆定版本。

iterator begin(); 
const_iterator begin() const; //This will be used . 
const_iterator cbegin() const;