在C++14中引入了
通常它的用法是允许
在寻找这个习语的“好”用法的例子时,我只能想到以下类似的事情(由Scott Meyers提供),即用于函数的返回类型推断。
这个新的语言特性还有其他哪些实用的例子吗?
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)];
}
这个新的语言特性还有其他哪些实用的例子吗?
decltype(auto)
来完成类似于template<class U, V> decltype(auto) first(std::pair<U, V>& p) { return p.first; }
的功能,但我后来意识到必须使用return (p.first);
,这令人惊讶地起作用了(但如果我没记错的话,这甚至是有意的)。 - dypdecltype(auto)
可能会导致某些东西被复制/移动到声明的对象中,与预期相反,从而增加意外事故的潜在风险。 - underscore_dcontainer
实际上是一个 rvalue,我认为使用 decltype(auto) 可能会导致意外引用无效内存。然而,你可以通过 ContainerType 的值类型返回,并且副本省略应该会给你与 decltype(auto) 相同的东西,但可以安全地作为引用返回。https://godbolt.org/z/GsYjxs - Steve Bronder