C++ 了解std::forward重载是如何工作的

C++ 了解std::forward重载是如何工作的,c++,c++11,templates,c++14,forward,C++,C++11,Templates,C++14,Forward,我想再次检查我是否正确理解了前向重载的工作原理 template< class T > constexpr T&& forward( std::remove_reference_t<T>& t ) noexcept; template< class T > constexpr T&& forward( std::remove_reference_t<T>&& t ) noexcept; 因

我想再次检查我是否正确理解了前向重载的工作原理

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

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

因此,我们将为我们的案例选择第一个。如果我们只调用
4
将指定相同的重载,但将选择第二个版本。所以第一个重载总是捕获所有左值,第二个重载总是捕获所有右值。正确吗?

是。几乎。您不能只调用
转发

如果使用局部变量
n
调用
foward
,例如
int

int n;
forward(n);
您会得到一个编译错误。如果您呼叫向前:

同样,编译错误,如
T
,无法推断,但如果我们这样做了

forward<int>(4);

这将选择第二个过载。

您的假设是正确的。我推荐使用。谢谢你的解释。我也检查过了,如果要向前呼叫,预计会有错误(8);但是你能解释一下你不合理的例子吗?Whta是运算符int&()&;中的最后一个与符号;?
int n;
forward<int>(n);
constexpr int&& forward<int>(int& t)noexcept;
constexpr int&& forward<int>(int&& t)noexcept;
forward(4);
forward<int>(4);
constexpr int&& forward<int>(int& t)noexcept;
constexpr int&& forward<int>(int&& t)noexcept;
int n;
forward<int&>(n);
constexpr int& forward<int&>(int& t)noexcept;
constexpr int& forward<int&>(int&& t)noexcept;
struct unreasonable {
  operator int&&()&;
};
unreasonable r;
forward<int>(r);