根据 this link , std::forward
不允许模板参数推导,而 std::remove_reference
正在帮助我们实现这一目标。但是,使用 remove_reference
如何防止此处发生模板推导?
template <class S>
S&& forward(typename std::remove_reference<S>::type& t) noexcept
{
return static_cast<S&&>(t);
}
最佳答案
S
在表达式 typename std::remove_reference<S>::type
中是一个非推导上下文(特别是因为 S
出现在使用 qualified-id 指定类型的nested-name-specifier 中).顾名思义,非推导上下文是无法推导模板参数的上下文。
这个案例提供了一个简单的例子来理解为什么。假设我有:
int i;
forward(i);
什么会 S
是?可能是 int
, int&
, 或 int&&
- 所有这些类型都会为函数产生正确的参数类型。编译器根本不可能确定哪个 S
你真的是说这里 - 所以它不会尝试。它是不可推导的,因此您必须明确提供哪个 S
你的意思是:
forward<int&>(i); // oh, got it, you meant S=int&
关于c++ - remove_reference 如何禁用模板参数推导?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37418089/