为什么 std::forward() 不推断类型?
Why std::forward() doesn't deduce type?
下面是代码。为什么如果我用S&
替换typename remove_reference<S>::type&
,它不会很好地工作?(我的意思是一种类型会被推断错误)
如果我传递一个右值(让int为int),那么S
将被推导为int
,a
的类型是int&
,forward()
返回int&&
(右值)。
如果我传递一个左值(int
),则S
将被推导为int&
,a
的类型为int& & ->int&
,forward()
返回int& &&->int&
。一切都很好,为什么我们需要remove_reference
?
template<class S>
S&& forward(typename remove_reference<S>::type& a) noexcept
{
return static_cast<S&&>(a);
}
考虑forward
:的原始用例
template<class T>
void f(T&& t) { g(std::forward<T>(t)); }
t
有一个名称,所以它是f
中的一个左值,即使它绑定到一个右值。如果允许forward
推导类型,那么人们会很想写std::forward(t)
,但实际上并没有得到他们期望的完美转发。
此外,你的分析也不正确。template<class S> void f(S& t);
不与右值结合。std::forward
实际上是一对重载——您所指的那个重载只取lvalues,而
template <class T> constexpr T&& forward(remove_reference_t<T>&& t) noexcept;
处理右值。
相关文章:
- 从类型std::函数传递变量失败,尽管调用方期望的类型完全相同
- 错误 C2679:二进制"<<":未找到采用类型 'std::string_view' 的右侧操作数的运算符(或者没有可接受的转换)
- 错误:无法传递非平凡类型"std::string"的对象和更多错误
- 与'operator<<'不匹配(操作数类型'std::ostream {aka std::basic_ostream<char>}'
- std::函数指针错误:无法将 &A::a 转换为类型 std::function<>&&
- 包括<字符串>,使用不完整的类型"std::string"
- 与"operator<<"不匹配(操作数类型'std::ostream'
- 错误:类型"std::__1::basic_string<char>"不提供呼叫运算符
- 错误:请求从"Mstream"转换为非标量类型"std::string {aka std::basic_string<char>}"
- 错误:移动文件时'QString'为非标量类型"std::__cxx11::字符串"
- CLion 无法解析类型 std::unordered_map,即使它提示我包含标头并且编译工作
- 字符串C :libc abi.dylib:终止未被发现的类型std :: out_of_range:basic
- 返回类型 std::optional<std::variant<...>>
- 变量具有不完整的类型std :: String;string.h有很多错误
- 对类型 'A *' 的非常量左值引用不能绑定到不相关的类型 'std::shared_ptr<A>' 的值
- 来自类型为std::basic_string::const_iterator的非常量引用的无效初始化,并且<char>来自类型std::basic_string<char>::
- 类型"std::array<char,6>"和"char"不兼容
- 此错误的含义是什么:从 'char* [40] 转换为非标量类型 'std::string
- 使用 TypedEq() 匹配类型 std::vector<std::vector>
- 如何修复错误:请求从"void"转换为非标量类型"std::vector<int>"