2022-06-30 10:23:03 +08:00
<!DOCTYPE HTML>
< html lang = "zh" class = "sidebar-visible no-js light" >
< head >
<!-- Book generated using mdBook -->
< meta charset = "UTF-8" >
2022-07-02 13:21:48 +08:00
< title > Item 3:理解decltype - Effective Modern C++< / title >
2022-06-30 10:23:03 +08:00
<!-- Custom HTML head -->
< meta content = "text/html; charset=utf-8" http-equiv = "Content-Type" >
< meta name = "description" content = "" >
< meta name = "viewport" content = "width=device-width, initial-scale=1" >
< meta name = "theme-color" content = "#ffffff" / >
< link rel = "icon" href = "../favicon.svg" >
< link rel = "shortcut icon" href = "../favicon.png" >
< link rel = "stylesheet" href = "../css/variables.css" >
< link rel = "stylesheet" href = "../css/general.css" >
< link rel = "stylesheet" href = "../css/chrome.css" >
< link rel = "stylesheet" href = "../css/print.css" media = "print" >
<!-- Fonts -->
< link rel = "stylesheet" href = "../FontAwesome/css/font-awesome.css" >
< link rel = "stylesheet" href = "../fonts/fonts.css" >
<!-- Highlight.js Stylesheets -->
< link rel = "stylesheet" href = "../highlight.css" >
< link rel = "stylesheet" href = "../tomorrow-night.css" >
< link rel = "stylesheet" href = "../ayu-highlight.css" >
<!-- Custom theme stylesheets -->
<!-- MathJax -->
< script async type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML" > < / script >
< / head >
< body >
<!-- Provide site root to javascript -->
< script type = "text/javascript" >
var path_to_root = "../";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
< / script >
<!-- Work around some values being stored in localStorage wrapped in quotes -->
< script type = "text/javascript" >
try {
var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') & & theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') & & sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
< / script >
<!-- Set the theme before any content is loaded, prevents flash -->
< script type = "text/javascript" >
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('no-js')
html.classList.remove('light')
html.classList.add(theme);
html.classList.add('js');
< / script >
<!-- Hide / unhide sidebar before it is displayed -->
< script type = "text/javascript" >
var html = document.querySelector('html');
var sidebar = 'hidden';
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
}
html.classList.remove('sidebar-visible');
html.classList.add("sidebar-" + sidebar);
< / script >
< nav id = "sidebar" class = "sidebar" aria-label = "Table of contents" >
< div class = "sidebar-scrollbox" >
2022-07-02 13:21:48 +08:00
< ol class = "chapter" > < li class = "chapter-item expanded " > < a href = "../Introduction.html" > 简介< / a > < / li > < li class = "chapter-item expanded " > < div > 第一章 类型推导< / div > < / li > < li > < ol class = "section" > < li class = "chapter-item expanded " > < a href = "../1.DeducingTypes/item1.html" > Item 1:理解模板类型推导< / a > < / li > < li class = "chapter-item expanded " > < a href = "../1.DeducingTypes/item2.html" > Item 2:理解auto类型推导< / a > < / li > < li class = "chapter-item expanded " > < a href = "../1.DeducingTypes/item3.html" class = "active" > Item 3:理解decltype< / a > < / li > < li class = "chapter-item expanded " > < a href = "../1.DeducingTypes/item4.html" > Item 4:学会查看类型推导结果< / a > < / li > < / ol > < / li > < li class = "chapter-item expanded " > < div > 第二章 auto< / div > < / li > < li > < ol class = "section" > < li class = "chapter-item expanded " > < a href = "../2.Auto/item5.html" > Item 5:优先考虑auto而非显式类型声明< / a > < / li > < li class = "chapter-item expanded " > < a href = "../2.Auto/item6.html" > Item 6:auto推导若非己愿, 使用显式类型初始化惯用法< / a > < / li > < / ol > < / li > < li class = "chapter-item expanded " > < div > 第三章 移步现代C++< / div > < / li > < li > < ol class = "section" > < li class = "chapter-item expanded " > < a href = "../3.MovingToModernCpp/item7.html" > Item 7:区别使用()和{}创建对象< / a > < / li > < li class = "chapter-item expanded " > < a href = "../3.MovingToModernCpp/item8.html" > Item 8:优先考虑nullptr而非0和NULL< / a > < / li > < li class = "chapter-item expanded " > < a href = "../3.MovingToModernCpp/item9.html" > Item 9:优先考虑别名声明而非typedefs< / a > < / li > < li class = "chapter-item expanded " > < a href = "../3.MovingToModernCpp/item10.html" > Item 10:优先考虑限域枚举而非未限域枚举< / a > < / li > < li class = "chapter-item expanded " > < a href = "../3.MovingToModernCpp/item11.html" > Item 11:优先考虑使用deleted函数而非使用未定义的私有声明< / a > < / li > < li class = "chapter-item expanded " > < a href = "../3.MovingToModernCpp/item12.html" > Item 12:使用override声明重载函数< / a > < / li > < li class = "chapter-item expanded " > < a href = "../3.MovingToModernCpp/item13.html" > Item 13:优先考虑const_iterator而非iterator< / a > < / li > < li class = "chapter-item expanded " > < a href = "../3.MovingToModernCpp/item14.html" > Item 14:如果函数不抛出异常请使用noexcept< / a > < / li > < li class = "chapter-item expanded " > < a href = "../3.MovingToModernCpp/item15.html" > Item 15:尽可能的使用constexpr< / a > < / li > < li class = "chapter-item expanded " > < a href = "../3.MovingToModernCpp/item16.html" > Item 16:让const成员函数线程安全< / a > < / li > < li class = "chapter-item expanded " > < a href = "../3.MovingToModernCpp/item17.html" > Item 17:理解特殊成员函数函数的生成< / a > < / li > < / ol > < / li > < li class = "chapter-item expanded " > < div > 第四章 智能指针< / div > < / li > < li > < ol class = "section" > < li class = "chapter-item expanded " > < a href = "../4.SmartPointers/item18.html" > Item 18:对于独占资源使用std::unique_ptr< / a > < / li > < li class = "chapter-item expanded " > < a href = "../4.SmartPointers/item19.html" > Item 19:对于共享资源使用std::shared_ptr< / a > < / li > < li class = "chapter-item expanded " > < a href = "../4.SmartPointers/item20.html" > Item 20:当std::shard_ptr可能悬空时使用std::weak_ptr< / a > < / li > < li class = "chapter-item expanded " > < a href = "../4.SmartPointers/item21.html" > Item 21:优先考虑使用std::make_unique和std::make_shared而非new< / a > < / li > < li class = "chapter-item expanded " > < a href = "../4.SmartPointers/item22.html" > Item 22:当使用Pimpl惯用法, 请在实现文件中定义特殊成员函数< / a > < / li > < / ol > < / li > < li class = "chapter-item expanded " > < div > 第五章 右值引用,移动语义,完美转发< / div > < / li > < li > < ol class = "section" > < li class = "chapter-item expanded " > < a href = "../5.RRefMovSemPerfForw/item23.html" > Item 23:理解std::move和std::forward< / a > < / li > < li class = "chapter-item expanded " > < a href = "../5.RRefMovSemPerfForw/item24.html" > Item 24:区别通用引用和右值引用< / a > < / li > < li class = "chapter-item expanded " > < a href = "../5.RRefMovSemPerfForw/item25.html" > Item 25:对于右值引用使用std::move, 对于通用引用使用std::forward< / a > < / li > < li class = "chapter-item expanded " > < a href = "../5.
2022-06-30 10:23:03 +08:00
< / div >
< div id = "sidebar-resize-handle" class = "sidebar-resize-handle" > < / div >
< / nav >
< div id = "page-wrapper" class = "page-wrapper" >
< div class = "page" >
< div id = "menu-bar-hover-placeholder" > < / div >
< div id = "menu-bar" class = "menu-bar sticky bordered" >
< div class = "left-buttons" >
< button id = "sidebar-toggle" class = "icon-button" type = "button" title = "Toggle Table of Contents" aria-label = "Toggle Table of Contents" aria-controls = "sidebar" >
< i class = "fa fa-bars" > < / i >
< / button >
< button id = "theme-toggle" class = "icon-button" type = "button" title = "Change theme" aria-label = "Change theme" aria-haspopup = "true" aria-expanded = "false" aria-controls = "theme-list" >
< i class = "fa fa-paint-brush" > < / i >
< / button >
< ul id = "theme-list" class = "theme-popup" aria-label = "Themes" role = "menu" >
< li role = "none" > < button role = "menuitem" class = "theme" id = "light" > Light (default)< / button > < / li >
< li role = "none" > < button role = "menuitem" class = "theme" id = "rust" > Rust< / button > < / li >
< li role = "none" > < button role = "menuitem" class = "theme" id = "coal" > Coal< / button > < / li >
< li role = "none" > < button role = "menuitem" class = "theme" id = "navy" > Navy< / button > < / li >
< li role = "none" > < button role = "menuitem" class = "theme" id = "ayu" > Ayu< / button > < / li >
< / ul >
< button id = "search-toggle" class = "icon-button" type = "button" title = "Search. (Shortkey: s)" aria-label = "Toggle Searchbar" aria-expanded = "false" aria-keyshortcuts = "S" aria-controls = "searchbar" >
< i class = "fa fa-search" > < / i >
< / button >
< / div >
< h1 class = "menu-title" > Effective Modern C++< / h1 >
< div class = "right-buttons" >
< a href = "../print.html" title = "Print this book" aria-label = "Print this book" >
< i id = "print-button" class = "fa fa-print" > < / i >
< / a >
2022-09-08 16:47:52 +08:00
< a href = "https://github.com/CnTransGroup/EffectiveModernCppChinese" title = "Git repository" aria-label = "Git repository" >
< i id = "git-repository-button" class = "fa fa-github" > < / i >
< / a >
2022-06-30 10:23:03 +08:00
< / div >
< / div >
< div id = "search-wrapper" class = "hidden" >
< form id = "searchbar-outer" class = "searchbar-outer" >
< input type = "search" id = "searchbar" name = "searchbar" placeholder = "Search this book ..." aria-controls = "searchresults-outer" aria-describedby = "searchresults-header" >
< / form >
< div id = "searchresults-outer" class = "searchresults-outer hidden" >
< div id = "searchresults-header" class = "searchresults-header" > < / div >
< ul id = "searchresults" >
< / ul >
< / div >
< / div >
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
< script type = "text/javascript" >
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
< / script >
< div id = "content" class = "content" >
< main >
< h2 id = "条款三理解decltype" > < a class = "header" href = "#条款三理解decltype" > 条款三:理解< code > decltype< / code > < / a > < / h2 >
< p > < strong > Item 3: Understand decltype< / strong > < / p >
< p > < code > decltype< / code > 是一个奇怪的东西。给它一个名字或者表达式< code > decltype< / code > 就会告诉你这个名字或者表达式的类型。通常,它会精确的告诉你你想要的结果。但有时候它得出的结果也会让你挠头半天,最后只能求助网上问答或参考资料寻求启示。< / p >
< p > 我们将从一个简单的情况开始,没有任何令人惊讶的情况。相比模板类型推导和< code > auto< / code > 类型推导(参见< a href = "https://github.com/kelthuzadx/EffectiveModernCppChinese/blob/master/1.DeducingTypes/item1.md" > Item1< / a > 和< a href = "https://github.com/kelthuzadx/EffectiveModernCppChinese/blob/master/1.DeducingTypes/item2.md" > Item2< / a > ) , < code > decltype< / code > 只是简单的返回名字或者表达式的类型:< / p >
< pre > < code class = "language-cpp" > const int i = 0; //decltype(i)是const int
bool f(const Widget& w); //decltype(w)是const Widget&
//decltype(f)是bool(const Widget& )
struct Point{
int x,y; //decltype(Point::x)是int
}; //decltype(Point::y)是int
Widget w; //decltype(w)是Widget
if (f(w))… //decltype(f(w))是bool
template< typename T> //std::vector的简化版本
class vector{
public:
…
T& operator[](std::size_t index);
…
};
vector< int> v; //decltype(v)是vector< int>
…
if (v[0] == 0)… //decltype(v[0])是int&
< / code > < / pre >
< p > 看见了吧?没有任何奇怪的东西。< / p >
< p > 在C++11中, < code > decltype< / code > 最主要的用途就是用于声明函数模板,而这个函数返回类型依赖于形参类型。举个例子,假定我们写一个函数,一个形参为容器,一个形参为索引值,这个函数支持使用方括号的方式(也就是使用“< code > []< / code > ”)访问容器中指定索引值的数据,然后在返回索引操作的结果前执行认证用户操作。函数的返回类型应该和索引操作返回的类型相同。< / p >
< p > 对一个< code > T< / code > 类型的容器使用< code > operator[]< / code > 通常会返回一个< code > T& < / code > 对象,比如< code > std::deque< / code > 就是这样。但是< code > std::vector< / code > 有一个例外,对于< code > std::vector< bool> < / code > , < code > operator[]< / code > 不会返回< code > bool& < / code > , 它会返回一个全新的对象( 译注: MSVC的STL实现中返回的是< code > std::_Vb_reference< std::_Wrap_alloc< std::allocator< unsigned int> > > < / code > 对象)。关于这个问题的详细讨论请参见< a href = "https://github.com/kelthuzadx/EffectiveModernCppChinese/blob/master/2.Auto/item6.md" > Item6< / a > ,这里重要的是我们可以看到对一个容器进行< code > operator[]< / code > 操作返回的类型取决于容器本身。< / p >
< p > 使用< code > decltype< / code > 使得我们很容易去实现它,这是我们写的第一个版本,使用< code > decltype< / code > 计算返回类型,这个模板需要改良,我们把这个推迟到后面:< / p >
< pre > < code class = "language-cpp" > template< typename Container, typename Index> //可以工作,
auto authAndAccess(Container& c, Index i) //但是需要改良
-> decltype(c[i])
{
authenticateUser();
return c[i];
}
< / code > < / pre >
< p > 函数名称前面的< code > auto< / code > 不会做任何的类型推导工作。相反的, 他只是暗示使用了C++11的< strong > 尾置返回类型< / strong > 语法,即在函数形参列表后面使用一个”< code > -> < / code > “符号指出函数的返回类型,尾置返回类型的好处是我们可以在函数返回类型中使用函数形参相关的信息。在< code > authAndAccess< / code > 函数中,我们使用< code > c< / code > 和< code > i< / code > 指定返回类型。如果我们按照传统语法把函数返回类型放在函数名称之前,< code > c< / code > 和< code > i< / code > 就未被声明所以不能使用。< / p >
< p > 在这种声明中,< code > authAndAccess< / code > 函数返回< code > operator[]< / code > 应用到容器中返回的对象的类型,这也正是我们期望的结果。< / p >
< p > C++11允许自动推导单一语句的< em > lambda< / em > 表达式的返回类型, C++14扩展到允许自动推导所有的< em > lambda< / em > 表达式和函数,甚至它们内含多条语句。对于< code > authAndAccess< / code > 来说这意味着在C++14标准下我们可以忽略尾置返回类型, 只留下一个< code > auto< / code > 。使用这种声明形式, auto标示这里会发生类型推导。更准确的说, 编译器将会从函数实现中推导出函数的返回类型。< / p >
< pre > < code class = "language-cpp" > template< typename Container, typename Index> //C++14版本,
auto authAndAccess(Container& c, Index i) //不那么正确
{
authenticateUser();
return c[i]; //从c[i]中推导返回类型
}
< / code > < / pre >
< p > < a href = "https://github.com/kelthuzadx/EffectiveModernCppChinese/blob/master/1.DeducingTypes/item2.md" > Item2< / a > 解释了函数返回类型中使用< code > auto< / code > ,编译器实际上是使用的模板类型推导的那套规则。如果那样的话这里就会有一些问题。正如我们之前讨论的,< code > operator[]< / code > 对于大多数< code > T< / code > 类型的容器会返回一个< code > T& < / code > ,但是< a href = "https://github.com/kelthuzadx/EffectiveModernCppChinese/blob/master/1.DeducingTypes/item1.md" > Item1< / a > 解释了在模板类型推导期间, 表达式的引用性( reference-ness) 会被忽略。基于这样的规则, 考虑它会对下面用户的代码有哪些影响: < / p >
< pre > < code class = "language-cpp" > std::deque< int> d;
…
authAndAccess(d, 5) = 10; //认证用户, 返回d[5],
//然后把10赋值给它
//无法通过编译器!
< / code > < / pre >
< p > 在这里< code > d[5]< / code > 本该返回一个< code > int& < / code > ,但是模板类型推导会剥去引用的部分,因此产生了< code > int< / code > 返回类型。函数返回的那个< code > int< / code > 是一个右值, 上面的代码尝试把10赋值给右值< code > int< / code > , C++11禁止这样做, 所以代码无法编译。< / p >
< p > 要想让< code > authAndAccess< / code > 像我们期待的那样工作,我们需要使用< code > decltype< / code > 类型推导来推导它的返回值,即指定< code > authAndAccess< / code > 应该返回一个和< code > c[i]< / code > 表达式类型一样的类型。C++期望在某些情况下当类型被暗示时需要使用< code > decltype< / code > 类型推导的规则, C++14通过使用< code > decltype(auto)< / code > 说明符使得这成为可能。我们第一次看见< code > decltype(auto)< / code > 可能觉得非常的矛盾(到底是< code > decltype< / code > 还是< code > auto< / code > ?),实际上我们可以这样解释它的意义:< code > auto< / code > 说明符表示这个类型将会被推导,< code > decltype< / code > 说明< code > decltype< / code > 的规则将会被用到这个推导过程中。因此我们可以这样写< code > authAndAccess< / code > : < / p >
< pre > < code class = "language-cpp" > template< typename Container, typename Index> //C++14版本,
decltype(auto) //可以工作,
authAndAccess(Container& c, Index i) //但是还需要
{ //改良
authenticateUser();
return c[i];
}
< / code > < / pre >
< p > 现在< code > authAndAccess< / code > 将会真正的返回< code > c[i]< / code > 的类型。现在事情解决了,一般情况下< code > c[i]< / code > 返回< code > T& < / code > , < code > authAndAccess< / code > 也会返回< code > T& < / code > ,特殊情况下< code > c[i]< / code > 返回一个对象,< code > authAndAccess< / code > 也会返回一个对象。< / p >
< p > < code > decltype(auto)< / code > 的使用不仅仅局限于函数返回类型,当你想对初始化表达式使用< code > decltype< / code > 推导的规则,你也可以使用:< / p >
< pre > < code class = "language-cpp" > Widget w;
const Widget& cw = w;
auto myWidget1 = cw; //auto类型推导
//myWidget1的类型为Widget
decltype(auto) myWidget2 = cw; //decltype类型推导
//myWidget2的类型是const Widget&
< / code > < / pre >
< p > 但是这里有两个问题困惑着你。一个是我之前提到的< code > authAndAccess< / code > 的改良至今都没有描述。让我们现在加上它。< / p >
< p > 再看看C++14版本的< code > authAndAccess< / code > 声明:< / p >
< pre > < code class = "language-cpp" > template< typename Container, typename Index>
decltype(auto) authAndAccess(Container& c, Index i);
< / code > < / pre >
< p > 容器通过传引用的方式传递非常量左值引用( lvalue-reference-to-non-< strong > const< / strong > ) , 因为返回一个引用允许用户可以修改容器。但是这意味着在不能给这个函数传递右值容器, 右值不能被绑定到左值引用上( 除非这个左值引用是一个const( lvalue-references-to-< strong > const< / strong > ),但是这里明显不是)。< / p >
< p > 公认的向< code > authAndAccess< / code > 传递一个右值是一个< a href = "https://en.wikipedia.org/wiki/Edge_case" > edge case< / a > (译注:在极限操作情况下会发生的事情,类似于会发生但是概率较小的事情)。一个右值容器,是一个临时对象,通常会在< code > authAndAccess< / code > 调用结束被销毁,这意味着< code > authAndAccess< / code > 返回的引用将会成为一个悬置的( dangle) 引用。但是使用向< code > authAndAccess< / code > 传递一个临时变量也并不是没有意义,有时候用户可能只是想简单的获得临时容器中的一个元素的拷贝,比如这样:< / p >
< pre > < code class = "language-cpp" > std::deque< std::string> makeStringDeque(); //工厂函数
//从makeStringDeque中获得第五个元素的拷贝并返回
auto s = authAndAccess(makeStringDeque(), 5);
< / code > < / pre >
< p > 要想支持这样使用< code > authAndAccess< / code > 我们就得修改一下当前的声明使得它支持左值和右值。重载是一个不错的选择(一个函数重载声明为左值引用,另一个声明为右值引用),但是我们就不得不维护两个重载函数。另一个方法是使< code > authAndAccess< / code > 的引用可以绑定左值和右值,< a href = "https://github.com/kelthuzadx/EffectiveModernCppChinese/blob/master/5.RRefMovSemPerfForw/item24.md" > Item24< / a > 解释了那正是通用引用能做的,所以我们这里可以使用通用引用进行声明:< / p >
< pre > < code class = "language-cpp" > template< typename Containter, typename Index> //现在c是通用引用
decltype(auto) authAndAccess(Container& & c, Index i);
< / code > < / pre >
< p > 在这个模板中, 我们不知道我们操纵的容器的类型是什么, 那意味着我们同样不知道它使用的索引对象( index objects) 的类型, 对一个未知类型的对象使用传值通常会造成不必要的拷贝, 对程序的性能有极大的影响, 还会造成对象切片行为( 参见< a href = "https://github.com/kelthuzadx/EffectiveModernCppChinese/blob/master/8.Tweaks/item41.md" > item41< / a > ),以及给同事落下笑柄。但是就容器索引来说,我们遵照标准模板库对于索引的处理是有理由的(比如< code > std::string< / code > , < code > std::vector< / code > 和< code > std::deque< / code > 的< code > operator[]< / code > ),所以我们坚持传值调用。< / p >
< p > 然而,我们还需要更新一下模板的实现,让它能听从< a href = "https://github.com/kelthuzadx/EffectiveModernCppChinese/blob/master/5.RRefMovSemPerfForw/item25.md" > Item25< / a > 的告诫应用< code > std::forward< / code > 实现通用引用:< / p >
< pre > < code class = "language-cpp" > template< typename Container, typename Index> //最终的C++14版本
decltype(auto)
authAndAccess(Container& & c, Index i)
{
authenticateUser();
return std::forward< Container> (c)[i];
}
< / code > < / pre >
< p > 这样就能对我们的期望交上一份满意的答卷, 但是这要求编译器支持C++14。如果你没有这样的编译器, 你还需要使用C++11版本的模板, 它看起来和C++14版本的极为相似, 除了你不得不指定函数返回类型之外: < / p >
< pre > < code class = "language-cpp" > template< typename Container, typename Index> //最终的C++11版本
auto
authAndAccess(Container& & c, Index i)
-> decltype(std::forward< Container> (c)[i])
{
authenticateUser();
return std::forward< Container> (c)[i];
}
< / code > < / pre >
< p > 另一个问题是就像我在条款的开始唠叨的那样,< code > decltype< / code > 通常会产生你期望的结果,但并不总是这样。在< strong > 极少数情况下< / strong > 它产生的结果可能让你很惊讶。老实说如果你不是一个大型库的实现者你不太可能会遇到这些异常情况。< / p >
< p > 为了< strong > 完全< / strong > 理解< code > decltype< / code > 的行为,你需要熟悉一些特殊情况。它们大多数都太过晦涩以至于几乎没有书进行有过权威的讨论,这本书也不例外,但是其中的一个会让我们更加理解< code > decltype< / code > 的使用。< / p >
< p > 将< code > decltype< / code > 应用于变量名会产生该变量名的声明类型。虽然变量名都是左值表达式,但这不会影响< code > decltype< / code > 的行为。(译者注:这里是说对于单纯的变量名,< code > decltype< / code > 只会返回变量的声明类型)然而,对于比单纯的变量名更复杂的左值表达式,< code > decltype< / code > 可以确保报告的类型始终是左值引用。也就是说,如果一个不是单纯变量名的左值表达式的类型是< code > T< / code > ,那么< code > decltype< / code > 会把这个表达式的类型报告为< code > T& < / code > 。这几乎没有什么太大影响,因为大多数左值表达式的类型天生具备一个左值引用修饰符。例如,返回左值的函数总是返回左值引用。< / p >
< p > 这个行为暗含的意义值得我们注意,在:< / p >
< pre > < code class = "language-cpp" > int x = 0;
< / code > < / pre >
< p > 中,< code > x< / code > 是一个变量的名字,所以< code > decltype(x)< / code > 是< code > int< / code > 。但是如果用一个小括号包覆这个名字,比如这样< code > (x)< / code > ,就会产生一个比名字更复杂的表达式。对于名字来说,< code > x< / code > 是一个左值, C++11定义了表达式< code > (x)< / code > 也是一个左值。因此< code > decltype((x))< / code > 是< code > int& < / code > 。用小括号覆盖一个名字可以改变< code > decltype< / code > 对于名字产生的结果。< / p >
< p > 在C++11中这稍微有点奇怪, 但是由于C++14允许了< code > decltype(auto)< / code > 的使用,这意味着你在函数返回语句中细微的改变就可以影响类型的推导:< / p >
< pre > < code class = "language-cpp" > decltype(auto) f1()
{
int x = 0;
…
return x; //decltype(x) 是int, 所以f1返回int
}
decltype(auto) f2()
{
int x = 0;
return (x); //decltype((x))是int& , 所以f2返回int&
}
< / code > < / pre >
< p > 注意不仅< code > f2< / code > 的返回类型不同于< code > f1< / code > ,而且它还引用了一个局部变量!这样的代码将会把你送上未定义行为的特快列车,一辆你绝对不想上第二次的车。< / p >
< p > 当使用< code > decltype(auto)< / code > 的时候一定要加倍的小心,在表达式中看起来无足轻重的细节将会影响到< code > decltype(auto)< / code > 的推导结果。为了确认类型推导是否产出了你想要的结果,请参见< a href = "https://github.com/kelthuzadx/EffectiveModernCppChinese/blob/master/1.DeducingTypes/item4.md" > Item4< / a > 描述的那些技术。< / p >
< p > 同时你也不应该忽略< code > decltype< / code > 这块大蛋糕。没错,< code > decltype< / code > (单独使用或者与< code > auto< / code > 一起用)可能会偶尔产生一些令人惊讶的结果,但那毕竟是少数情况。通常,< code > decltype< / code > 都会产生你想要的结果,尤其是当你对一个名字使用< code > decltype< / code > 时,因为在这种情况下,< code > decltype< / code > 只是做一件本分之事:它产出名字的声明类型。< / p >
< p > < strong > 请记住:< / strong > < / p >
< ul >
< li > < code > decltype< / code > 总是不加修改的产生变量或者表达式的类型。< / li >
< li > 对于< code > T< / code > 类型的不是单纯的变量名的左值表达式,< code > decltype< / code > 总是产出< code > T< / code > 的引用即< code > T& < / code > 。< / li >
< li > C++14支持< code > decltype(auto)< / code > ,就像< code > auto< / code > 一样,推导出类型,但是它使用< code > decltype< / code > 的规则进行推导。< / li >
< / ul >
< / main >
< nav class = "nav-wrapper" aria-label = "Page navigation" >
<!-- Mobile navigation buttons -->
< a rel = "prev" href = "../1.DeducingTypes/item2.html" class = "mobile-nav-chapters previous" title = "Previous chapter" aria-label = "Previous chapter" aria-keyshortcuts = "Left" >
< i class = "fa fa-angle-left" > < / i >
< / a >
< a rel = "next" href = "../1.DeducingTypes/item4.html" class = "mobile-nav-chapters next" title = "Next chapter" aria-label = "Next chapter" aria-keyshortcuts = "Right" >
< i class = "fa fa-angle-right" > < / i >
< / a >
< div style = "clear: both" > < / div >
< / nav >
< / div >
< / div >
< nav class = "nav-wide-wrapper" aria-label = "Page navigation" >
< a rel = "prev" href = "../1.DeducingTypes/item2.html" class = "nav-chapters previous" title = "Previous chapter" aria-label = "Previous chapter" aria-keyshortcuts = "Left" >
< i class = "fa fa-angle-left" > < / i >
< / a >
< a rel = "next" href = "../1.DeducingTypes/item4.html" class = "nav-chapters next" title = "Next chapter" aria-label = "Next chapter" aria-keyshortcuts = "Right" >
< i class = "fa fa-angle-right" > < / i >
< / a >
< / nav >
< / div >
< script type = "text/javascript" >
window.playground_copyable = true;
< / script >
< script src = "../elasticlunr.min.js" type = "text/javascript" charset = "utf-8" > < / script >
< script src = "../mark.min.js" type = "text/javascript" charset = "utf-8" > < / script >
< script src = "../searcher.js" type = "text/javascript" charset = "utf-8" > < / script >
< script src = "../clipboard.min.js" type = "text/javascript" charset = "utf-8" > < / script >
< script src = "../highlight.js" type = "text/javascript" charset = "utf-8" > < / script >
< script src = "../book.js" type = "text/javascript" charset = "utf-8" > < / script >
<!-- Custom JS scripts -->
< / body >
< / html >