【发布时间】:2014-06-10 22:41:12
【问题描述】:
考虑以下:
auto list = std::make_tuple(1, 2, 3, 4);
/// Work like a charm
template <class T>
auto test1(T &&brush) -> decltype(std::get<0>( std::forward<T>(brush) )) {
return std::get<0>( std::forward<T>(brush) );
}
/// And now - C++14 feature
/// fail to compile - return value(temporary), instead of l-reference
template <class T>
auto test2(T &&brush) {
return std::get<0>( std::forward<T>(brush) );
}
int main()
{
auto &t1 = test1(list);
auto &t2 = test2(list);
}
http://coliru.stacked-crooked.com/a/816dea1a0ed3e9ee
gcc 和 clang 都抛出错误:
main.cpp:26:11: error: non-const lvalue reference to type 'int' cannot bind to a temporary of type 'int'
auto &t2 = test2(list);
^ ~~~~~~~~~~~
它不应该像 decltype 那样工作吗?为什么不一样?
更新
如果是std::get,不就相当于这个吗? (我使用 gcc 4.8)
template <class T>
auto&& test2(T &&brush) {
return std::get<0>( std::forward<T>(brush) );
}
【问题讨论】:
-
test1和test2返回类型为int,不能绑定到int&。试试auto && t1或auto t1或auto const & t1 -
@BryanChen 为什么我不能引用 int 值?
-
@BryanChen
test1的返回类型是int&。decltype保留引用。这就是decltype(auto)和auto之间的区别。