首页 > 解决方案 > 需要帮助理解 std::forward

问题描述

C++ 中的完美转发和通用引用一文中,我有一个我不明白的时刻。在使用 std::forward 第一个案例解决完美转发段落中,我理解,但第二个没有。

The other case to handle is:

wrapper(42, 3.14f);
Here the arguments are rvalues, so T1 is deduced to int. We get the call func(forward<int>(e1), ...). Therefore, forward is instantiated with int and we get this version of it [3]:

int&& forward(int&& t) noexcept {
    return static_cast<int&&>(t);
}

包装是

template <typename T1, typename T2>
void wrapper(T1&& e1, T2&& e2) {
    func(forward<T1>(e1), forward<T2>(e2));
}

对于正向作者说在这种情况下使用了这个重载

template<class T>
T&& forward(typename std::remove_reference<T>::type& t) noexcept {
  return static_cast<T&&>(t);
}

所以在调用 wrapper(42, 3.14f); 我们有

void wrapper(int&& && e1, float&& && e2) {
        func(forward<T1>(e1), forward<T2>(e2));

推断为

void wrapper(int e1, float e2) {
        func(forward<int>(e1), forward<float>(e2));

然后调用其中之一。因为它是向前的(typename std::remove_reference::type& t)我们仍然有

int&& forward(typename std::remove_reference<int>::type& t) noexcept 
-->

int&& forward(typename int& t) noexcept 

于是又来了

return static_cast<int& &&>(t);

这将返回 int&。但是在这个例子中我们应该得到 int&& 。所以我显然不明白一些事情。对我来说,似乎 typename std::remove_reference::type& t 总是会返回引用,所以 forward 的返回总是return static_cast<T& &&>(t); 需要帮助。

标签: c++c++11templatesrvaluelvalue

解决方案


推荐阅读