简体   繁体   English

为什么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
}

My compiler is clang 7.0, compiled with c++17 . 我的编译器是clang 7.0,使用c++17编译。 The error message is: 错误消息是:

error : no matching function for call to 'f2'
  note: candidate template ignored:
        couldn't infer template argument 'T'

Why is f1 ok but f2 isn't? 为什么f1f2不能?

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>) , ie template<typename T> void f2(typename std::add_lvalue_reference<T>::type) , belongs to non-deduced context , which causes template argument deduction fails. std::add_lvalue_reference_t<T>被定义为typename std::add_lvalue_reference<T>::type ,然后对于template<typename T> void f2(Ref2<T>) ,即template<typename T> void f2(typename std::add_lvalue_reference<T>::type) ,属于非推导上下文 ,这导致模板参数推导失败。

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. 在以下情况下,用于构成P的类型,模板和非类型值不参与模板自变量的推导,而是使用在其他地方推导或明确指定的模板自变量。 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: 1)使用限定ID指定的类型的嵌套名称说明符(范围解析运算符::的所有内容):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM