【问题标题】:Why does std::add_lvalue_reference not behave as expected?为什么 std::add_lvalue_reference 的行为不符合预期?
【发布时间】:2019-05-09 18:45:48
【问题描述】:
#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 不行?

【问题讨论】:

    标签: c++ c++11 standards typetraits using-declaration


    【解决方案1】:

    std::add_lvalue_reference_t&lt;T&gt;定义为typename std::add_lvalue_reference&lt;T&gt;::type,那么对于template&lt;typename T&gt; void f2(Ref2&lt;T&gt;),即template&lt;typename T&gt; void f2(typename std::add_lvalue_reference&lt;T&gt;::type),属于non-deduced context,导致模板参数推导失败。

    在以下情况下,用于构成 P 的类型、模板和非类型值不参与模板参数推导,而是使用在其他地方推导或显式指定的模板参数。如果模板参数仅在非推导上下文中使用且未显式指定,则模板参数推导失败。

    1) 使用限定 ID 指定的类型的嵌套名称说明符(范围解析运算符 :: 左侧的所有内容):

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-17
      • 1970-01-01
      • 1970-01-01
      • 2012-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多