标准向前实施和参考崩溃 [英] std forward implementation and reference collapsing

查看:74
本文介绍了标准向前实施和参考崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在斯科特·迈耶斯(Scott Meyers)的书中,他提到了这样的标准向前执行(不符合标准)

in scott meyers book he mentioned an implementation for std forward that goes like this (non std conformant)

template <typename T>
T&& forward(typename remove_reference<T>::type& param)
{
   return static_cast<T&&>(param);
}

问题是为什么我们需要在这里删除引用?

The question is why do we need to remove reference here?

,因此典型的前向用法将在通用引用函数中如下所示:

so a typical forward usage would be in a universal reference function as follows:

template <typename T>
void f(T&& fparam)
{
    g(forward<T>(fparam));  // assume there is g function.
}

没有删除参考,前锋会像这样

without remove reference, the forward would look like this

template <typename T>
T&& forward(T& param);

现在,这两种情况是:


  1. fparam是右值,在这种情况下,f函数内部的T被推导为
    非引用对象类型,因此前向调用将
    左值引用作为参数,并将其转换为T&& (因为T是非引用)。

  1. fparam is rvalue in that case inside f function the T is deduced as non reference object type so the forward call take the param by lvalue reference and cast it to T&& (because T is non reference).

fparam是左值,然后在f内将T推导为T&。然后转发
将采用(作为参数)对左值引用的引用(合拢为左值
引用),则静态类型转换为T& &&还是lvalue
参考。

fparam is lvalue then inside f the T is deduced as T& then forward will take (as argument) a reference to an lvalue reference (collapsing to lvalue reference) then the static cast would be T& && which is again lvalue reference.

为什么我们需要从forward参数中删除参考?可能与禁止推导类型有关吗?

so why do we need to remove reference from param of forward? does it have to do with disallowing deducing types maybe? can somebody maybe give a detailed explanation.

被引用为重复项的问题不是,答案基本上是说std​​库使用remove引用,但是为什么呢?

The question that is referenced as duplicate is not, the answer basically says that the std library uses remove reference but why?

推荐答案


也许与禁止推导类型有关吗?

Does it have to do with disallowing deducing types maybe?

是的, typename std :: remove_reference< T> :: type 引入了 非推断上下文

Yes, typename std::remove_reference<T>::type introduces a non-deduced context. It prevents the user from mistakenly writing...

std::forward(something)

...并强迫他/她提供一个明确的模板参数:

...and forces him/her to provide an explicit template argument:

std::forward<T>(something)

这篇关于标准向前实施和参考崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆