亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

decltype(auto)有什么用?

decltype(auto)有什么用?

C++
吃雞游戲 2019-12-10 13:08:59
在c ++ 14中,decltype(auto)引入了慣用語。通常,它的用途是允許auto聲明使用decltype給定表達式上的規則。在搜索習慣用法的“示例”示例時,我只能想到以下內容(由Scott Meyers撰寫),即函數的返回類型推導:template<typename ContainerType, typename IndexType>                // C++14decltype(auto) grab(ContainerType&& container, IndexType&& index){  authenticateUser();  return std::forward<ContainerType>(container)[std::forward<IndexType>(index)];}還有其他使用此新語言功能的示例嗎?
查看完整描述

2 回答

?
慕勒3428872

TA貢獻1848條經驗 獲得超6個贊

在c ++ 14中,decltype(auto)引入了慣用語。


通常,它的用途是允許auto聲明使用decltype給定表達式上的規則。


在搜索習慣用法的“示例”示例時,我只能想到以下內容(由Scott Meyers撰寫),即函數的返回類型推導:


template<typename ContainerType, typename IndexType>                // C++14

decltype(auto) grab(ContainerType&& container, IndexType&& index)

{

  authenticateUser();

  return std::forward<ContainerType>(container)[std::forward<IndexType>(index)];

}

還有其他使用此新語言功能的示例嗎?


查看完整回答
反對 回復 2019-12-11
?
三國紛爭

TA貢獻1804條經驗 獲得超7個贊

從這里報價:


decltype(auto)主要用于推導轉發函數和類似包裝的返回類型,在這種情況下,您希望類型精確“跟蹤”正在調用的某些表達式。


例如,給定以下功能:


   string  lookup1();

   string& lookup2();

在C ++ 11中,我們可以編寫以下包裝函數,這些包裝函數記住保留返回類型的引用性:

   string  look_up_a_string_1() { return lookup1(); }

   string& look_up_a_string_2() { return lookup2(); }

在C ++ 14中,我們可以實現以下自動化:

   decltype(auto) look_up_a_string_1() { return lookup1(); }

   decltype(auto) look_up_a_string_2() { return lookup2(); }

但是,除此以外,decltype(auto)并不打算成為廣泛使用的功能。


特別是,盡管它可以用來聲明局部變量,但這樣做可能只是一個反模式,因為局部變量的引用性不應該依賴于初始化表達式。


另外,它對如何編寫return語句也很敏感。


例如,下面的兩個函數具有不同的返回類型:


   decltype(auto) look_up_a_string_1() { auto str = lookup1(); return str; }

   decltype(auto) look_up_a_string_2() { auto str = lookup2(); return(str); }

第一個返回string,第二個返回string&,這是對局部變量的引用str。

從提案中,您可以看到更多的預期用途。



查看完整回答
反對 回復 2019-12-11
  • 2 回答
  • 0 關注
  • 560 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號