c++ - 为什么 std::forward() 不推导类型?

标签 c++ c++11 reference rvalue

<分区>

下面是代码。为什么如果我替换 typename remove_reference<S>::type&S&它不会很好地工作? (我的意思是一个类型会被推错)

如果我传递一个右值(让 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 中的一个左值即使它绑定(bind)到右值。如果forward允许推断类型,那么人们会很想写 std::forward(t)而实际上并没有得到他们期望的完美转发。


另外,你的分析也不对。 template<class S> void f(S& t);不绑定(bind)到右值。 std::forward实际上是一对重载 - 你所指的那个只接受左值,并且

template <class T> constexpr T&& forward(remove_reference_t<T>&& t) noexcept;

处理右值。

关于c++ - 为什么 std::forward() 不推导类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25571769/

相关文章:

python - 如何创建不执行任何操作的函数引用

C++:将int的地址作为参数传递

c++ - C++ 中的字符串标记化,包括定界符

c++ - 从每列具有不同数量值的文件中读取值,C++

c++ - 随机字符串生成

c++ - C++11 中的异步构造函数

c++ - boost::asio::io_service::run 在没有工作时不返回

c++ - 重载可变长度模板函数的递归结束

c++ - 包装二进制缓冲区 - 可能没有多余的移动/复制?

html - 如何对 Emacs 进行编程以语法突出显示以数字指定的 html 字符引用