【问题标题】:How remove_reference disable template argument deductions?remove_reference 如何禁用模板参数扣除?
【发布时间】:2016-05-24 15:37:06
【问题描述】:

根据this linkstd::forward 不允许模板参数推导,std::remove_reference 正在帮助我们实现这一目标。但是这里使用remove_reference如何防止模板推导发生呢?

template <class S>
S&& forward(typename std::remove_reference<S>::type& t) noexcept
{
    return static_cast<S&&>(t);
}

【问题讨论】:

    标签: c++ templates c++11 perfect-forwarding


    【解决方案1】:
    表达式typename std::remove_reference&lt;S&gt;::type 中的

    S非推导上下文(特别是因为S 出现在指定类型的nested-name-specifier 中使用 qualified-id)。顾名思义,非推导上下文是不能推导模板参数的上下文。

    这个案例提供了一个简单的例子来理解原因。说我有:

    int i;
    forward(i);
    

    S 会是什么?它可能是intint&amp;int&amp;&amp;——所有这些类型都会为函数产生正确的参数类型。编译器根本不可能确定 which S 你在这里真正的意思 - 所以它不会尝试。这是不可推断的,因此您必须明确提供您的意思是哪个S

    forward<int&>(i); // oh, got it, you meant S=int&
    

    【讨论】:

    • “我可以有一个完全不相关的类型 Foo,我专门针对它使用 remove_reference&lt;Foo&gt; 来拥有类型 int。”这在技术上是 UB :)
    • @T.C.,为什么会是 UB?是不是“唯一”糟糕的设计,就像实现operator+ 进行类似减法的运算?或者可能是 UB,因为我们正在专门研究 std:: 函数?好的,就是这样:The behavior of a program that adds specializations for remove_reference is undefined.
    猜你喜欢
    • 1970-01-01
    • 2013-06-20
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多