decltype(auto)有什么用?

在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)];

}

还有其他使用此新语言功能的示例吗?


大话西游666
浏览 998回答 2
2回答

守着一只汪

从这里报价:decltype(auto)主要用于推导转发函数和类似包装的返回类型,在这种情况下,您希望类型精确“跟踪”正在调用的某些表达式。例如,给定以下功能:&nbsp; &nbsp;string&nbsp; lookup1();&nbsp; &nbsp;string& lookup2();在C ++ 11中,我们可以编写以下包装函数,这些包装函数记住保留返回类型的引用性:&nbsp; &nbsp;string&nbsp; look_up_a_string_1() { return lookup1(); }&nbsp; &nbsp;string& look_up_a_string_2() { return lookup2(); }在C ++ 14中,我们可以实现以下自动化:&nbsp; &nbsp;decltype(auto) look_up_a_string_1() { return lookup1(); }&nbsp; &nbsp;decltype(auto) look_up_a_string_2() { return lookup2(); }但是,除此以外,decltype(auto)并不打算成为广泛使用的功能。特别是,尽管它可以用来声明局部变量,但这样做可能只是一个反模式,因为局部变量的引用性不应该依赖于初始化表达式。另外,它对如何编写return语句也很敏感。例如,下面的两个函数具有不同的返回类型:&nbsp; &nbsp;decltype(auto) look_up_a_string_1() { auto str = lookup1(); return str; }&nbsp; &nbsp;decltype(auto) look_up_a_string_2() { auto str = lookup2(); return(str); }第一个返回string,第二个返回string&,这是对局部变量的引用str。从提案中,您可以看到更多的预期用途。
打开App,查看更多内容
随时随地看视频慕课网APP