转发引用可以使用别名模板作为别名吗?
Can a forwarding reference be aliased with an alias template?
这是我之前问题的延续:
似乎以下代码在 Clang 3.7.0 (demo) and GCC 6.0.0 (demo) 中都有效:
template <class T>
using forwarding_reference = T&&;
template <class T>
void foo(forwarding_reference<T>) {}
int main()
{
int i{};
foo(i);
foo(1);
}
编译器是否有权用别名模板替换转发引用,这可能是一种奇特的编写方式?
这确实符合标准。 §14.5.7/2:
When a template-id refers to the specialization of an alias template,
it is equivalent to the associated type obtained by substitution of
its template-arguments for the template-parameters in the type-id of
the alias template.
现在,考虑在模板参数推导期间,仅检查参数的类型(根据模板参数)- §14.8.2.1/1:
Template argument deduction is done by comparing each function
template parameter type (call it P
) with the type of the
corresponding argument of the call (call it A
) as described below.
根据第一个引用,参数的类型,即 forwarding_reference<T>
,等同于 T&&
。因此 P
是 T&&
并且在推导方面没有区别。
委员会在关于这种情况的缺陷报告中得出了同样的结论,#1700:
Because the types of the function parameters are the same, regardless
of whether written directly or via an alias template, deduction must
be handled the same way in both cases.
这是我之前问题的延续:
似乎以下代码在 Clang 3.7.0 (demo) and GCC 6.0.0 (demo) 中都有效:
template <class T>
using forwarding_reference = T&&;
template <class T>
void foo(forwarding_reference<T>) {}
int main()
{
int i{};
foo(i);
foo(1);
}
编译器是否有权用别名模板替换转发引用,这可能是一种奇特的编写方式?
这确实符合标准。 §14.5.7/2:
When a template-id refers to the specialization of an alias template, it is equivalent to the associated type obtained by substitution of its template-arguments for the template-parameters in the type-id of the alias template.
现在,考虑在模板参数推导期间,仅检查参数的类型(根据模板参数)- §14.8.2.1/1:
Template argument deduction is done by comparing each function template parameter type (call it
P
) with the type of the corresponding argument of the call (call itA
) as described below.
根据第一个引用,参数的类型,即 forwarding_reference<T>
,等同于 T&&
。因此 P
是 T&&
并且在推导方面没有区别。
委员会在关于这种情况的缺陷报告中得出了同样的结论,#1700:
Because the types of the function parameters are the same, regardless of whether written directly or via an alias template, deduction must be handled the same way in both cases.