为什么 std::add_lvalue_reference 没有按预期运行?
Why does std::add_lvalue_reference not behave as expected?
#include <type_traits>
template<typename T>
using Ref1 = T & ;
template<typename T>
using Ref2 = std::add_lvalue_reference_t<T>;
template<typename T>
void f1(Ref1<T>)
{}
template<typename T>
void f2(Ref2<T>)
{}
int main()
{
int n{};
f1(n); // ok
f2(n); // error
}
我的编译器是clang 7.0,用c++17
编译。错误信息是:
error : no matching function for call to 'f2'
note: candidate template ignored:
couldn't infer template argument 'T'
为什么 f1
可以但 f2
不行?
std::add_lvalue_reference_t<T>
is defined as typename std::add_lvalue_reference<T>::type
, then for template<typename T> void f2(Ref2<T>)
, i.e. template<typename T> void f2(typename std::add_lvalue_reference<T>::type)
, belongs to non-deduced context,导致模板实参推导失败
In the following cases, the types, templates, and non-type values that are used to compose P do not participate in template argument deduction, but instead use the template arguments that were either deduced elsewhere or explicitly specified. If a template parameter is used only in non-deduced contexts and is not explicitly specified, template argument deduction fails.
1) The nested-name-specifier (everything to the left of the scope resolution operator ::) of a type that was specified using a qualified-id:
#include <type_traits>
template<typename T>
using Ref1 = T & ;
template<typename T>
using Ref2 = std::add_lvalue_reference_t<T>;
template<typename T>
void f1(Ref1<T>)
{}
template<typename T>
void f2(Ref2<T>)
{}
int main()
{
int n{};
f1(n); // ok
f2(n); // error
}
我的编译器是clang 7.0,用c++17
编译。错误信息是:
error : no matching function for call to 'f2'
note: candidate template ignored:
couldn't infer template argument 'T'
为什么 f1
可以但 f2
不行?
std::add_lvalue_reference_t<T>
is defined as typename std::add_lvalue_reference<T>::type
, then for template<typename T> void f2(Ref2<T>)
, i.e. template<typename T> void f2(typename std::add_lvalue_reference<T>::type)
, belongs to non-deduced context,导致模板实参推导失败
In the following cases, the types, templates, and non-type values that are used to compose P do not participate in template argument deduction, but instead use the template arguments that were either deduced elsewhere or explicitly specified. If a template parameter is used only in non-deduced contexts and is not explicitly specified, template argument deduction fails.
1) The nested-name-specifier (everything to the left of the scope resolution operator ::) of a type that was specified using a qualified-id: