【发布时间】:2014-07-29 08:54:27
【问题描述】:
在 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)];
}
还有其他例子可以说明这种新的语言功能有用吗?
【问题讨论】:
-
这篇文章基本上建议尽量避免使用这种习惯用法,因为使用它时,您为编译器提供的优化选项较少stackoverflow.com/a/20092875/2485710
-
我曾经将
decltype(auto)用于类似于template<class U, V> decltype(auto) first(std::pair<U, V>& p) { return p.first; }的东西,尽管后来我意识到我必须使用return (p.first);,这令人惊讶地工作(但IIRC 这甚至是有意的)。 -
-
在您上面给出的示例中,如果
container实际上是一个右值,我认为使用 decltype(auto) 可能会导致意外引用悬挂。但是,您可以通过 ContainerType 的值类型返回,复制省略号应该给您与 decltype(auto) 相同的东西,但可以安全地作为参考 godbolt.org/z/GsYjxs -
是的,这是另一个例子,容器的内部值被销毁,但我们要求从函数godbolt.org/z/7jE5Me引用它
标签: c++ auto c++14 decltype return-type-deduction