在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)];
}
Run Code Online (Sandbox Code Playgroud)
这个新语言功能有用吗?
如果我有一个功能:
Foo& Bar()
{
return /// do something to create a non-temp Foo here and return a reference to it
}
Run Code Online (Sandbox Code Playgroud)
为什么是这样:
auto x = Bar(); /// probably calls copy ctor - haven't checked
Run Code Online (Sandbox Code Playgroud)
这不一样吗?
auto &x = Bar(); /// actually get a reference here
Run Code Online (Sandbox Code Playgroud)
(实际上,我希望第二个版本能够获得对引用的引用,这没什么意义.)
如果我明确地将类型指定x为值或引用,我将得到我期望的(当然).但是,我希望auto能够编译为返回类型Bar(),在这种情况下,它是一个引用.
有没有之间的隐式转换Foo和Foo&该进场吗?
(规范参考被接受了,虽然我已经厌倦了阅读委员会发言.)
(默认情况下,第二次使用时间机器将使C++通过引用传递.使用#pragma compatibility触发器编译C代码.ARGH.)