如何remove_reference禁用模板参数推导? [英] How remove_reference disable template argument deductions?
问题描述
根据此链接,禁止模板参数推导 std :: forward
和 std :: remove_reference
的帮助我们实现了这一目标。但是使用 remove_reference
如何防止模板推导在这里发生?
According to this link, template argument deduction disallowed for std::forward
and std::remove_reference
is helping us to achieve that. But how does using remove_reference
prevent template deduction from happening here?
template <class S>
S&& forward(typename std::remove_reference<S>::type& t) noexcept
{
return static_cast<S&&>(t);
}
推荐答案
表达式
是非推断上下文(具体来说因为 typename std :: remove_reference< S> :: type
中的S S
出现在嵌套名称说明符中,该类型使用 qualified-id 指定)。顾名思义,非推论上下文是无法推导模板参数的上下文。
S
in the expression typename std::remove_reference<S>::type
is a non-deduced context (specifically because S
appears in the nested-name-specifier of a type specified using a qualified-id). Non-deduced contexts are, as the name suggests, contexts in which the template argument cannot be deduced.
这种情况提供了一个简单的示例来理解原因。假设我有:
This case provides an easy example to understand why. Say I had:
int i;
forward(i);
S
是什么?可以是 int
, int&
或 int& -所有这些类型都将为函数产生正确的参数类型。编译器根本无法确定您真正在这里表示的哪个
S
-因此不会尝试。这是不可推论的,因此您必须明确提供您指的是 S
:
What would S
be? It could be int
, int&
, or int&&
- all of those types would yield the correct argument type for the function. It's simply impossible for the compiler to determine which S
you really mean here - so it doesn't try. It's non-deducible, so you have to explicitly provide which S
you mean:
forward<int&>(i); // oh, got it, you meant S=int&
这篇关于如何remove_reference禁用模板参数推导?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!