【发布时间】:2018-08-27 11:23:03
【问题描述】:
我不明白为什么以下代码无效。
#include <type_traits>
#include <tuple>
template<typename... Ts>
void funka( std::tuple<Ts...>&& v ) {
}
template<typename T>
void funkb( T&& v ) {
funka( std::forward<T>( v ) );
}
void funk() {
auto tup = std::tuple<int,int>( 1, 2 );
funkb( tup );
}
失败并出现此错误:
<source>: In instantiation of 'void funkb(T&&) [with T = std::tuple<int, int>&]':
<source>:24:16: required from here
<source>:10:10: error: cannot bind rvalue reference of type 'std::tuple<int, int>&&' to lvalue of type 'std::tuple<int, int>'
funka( std::forward<T>( v ) );
~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
如果我 forward 衰减,它将编译。
template<typename T>
void funkb( T&& v ) {
funka( std::forward<std::decay_t<T>>( v ) );
}
所以问题是。为什么那不是有效的代码?在我看来,funkb 和 funka 的结果参数类型似乎是相同的。
提前致谢
【问题讨论】:
-
&& 在 funka 中是一个右值引用,而在 funkb 中类似的 && 是一个转发引用。