簡體   English   中英

c ++ std :: forward在容器上調用operator []

[英]c++ std::forward on the container calling operator[]

在“有效的現代C ++”一書中,在第3項中寫了這段代碼:

template<typename Container, typename Index>
decltype(auto)
authAndAccess(Container&& c, Index i)
{
  authenticateUser();
  return std::forward<Container>(c)[i];
}

我不明白你為什么叫std::forward 如果c是一個右值引用,那么在rvalue而不是左值上調用operator[]會改變什么? 對我來說c[i]應該就夠了。

PS:當變量是函數的參數時,我理解std::forward的目的:

template<typename T, typename... Ts>
std::unique_ptr<T> make_unique(Ts&&... params)
{
  return std::unique_ptr<T>(new T(std::forward<Ts>(params)...));
}

對於rvalues和左值,Container的operator []可能已經過載。

auto Container::opeartor[](int i) && -> Container::value_type&;
auto Container::opeartor[](int i) & -> Container::value_type&;

如果是這樣,我們想確保如果用r值初始化c,我們在c上調用operator []的rvalue版本。 重載operator []對於左值和右值的行為不一定是不常見的,但它是可能的,所以在真正的通用代碼中,我們需要在將它轉發給operator []之前將std :: forward應用於c。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM