为什么在C ++ 0x右值引用的正向定义中使用标识? [英] Why use identity in forward definition for C++0x rvalue reference?

查看:71
本文介绍了为什么在C ++ 0x右值引用的正向定义中使用标识?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

右值引用简介中,转发的定义如下:

  template <typename T>
  struct identity { typedef T type; };

  template <typename T>
  T &&forward(typename identity<T>::type &&a) { return a; }

identity 类的作用是什么?为什么不呢?

What purpose does the identity class perform? Why not:

  template <typename T>
  T &&forward(T &&a) { return a; }


推荐答案

身份的目的是为了使 T 不可推论。也就是说,强制客户端在调用转发时显式提供 T

The purpose of identity was to make T non-deducible. That is, to force the client to explicitly supply T when calling forward.

forward(a);     // compile-time error
forward<A>(a);  // ok

之所以需要这样做,是因为模板参数是 switch ,客户​​端告诉编译器将参数作为左值或右值转发。如果您不小心忘记提供此信息,则左值总是作为左值返回,而右值总是作为左值返回。

The reason this is necessary is because the template parameter is the switch with which the client tells the compiler to forward the argument as either an lvalue or as an rvalue. If you accidentally forget to supply this information then lvalues are always returned as lvalues and rvalues are always returned as rvalues. While at first that may sound like what you want, it really isn't.

template <class T, class A1>
std::shared_ptr<T>
factory(A1&& a1)
{
    return std::shared_ptr<T>(new T(std::forward<A1>(a1)));
}

在上面的示例中, a1 始终是左值。但是 switch A1 可能是左值引用,也可能不是。如果它是左值引用,则将 a1 作为左值返回,否则,将 a1 作为右值返回。如果工厂的作者意外忘记提供A1,则在编译时使用 ident c会提醒他。

In the above example a1 is always an lvalue. But the "switch" A1 may or may not be an lvalue reference. If it is an lvalue reference, a1 gets returned as an lvalue, otherwise a1 gets returned as an rvalue. If the author of factory accidentally forgets to supply A1, the use of identity reminds him at compile time.

注意:最终草案缺少身份,但是在同一位置出于相同目的使用 remove_reference

Note: The final draft lacks identity, but uses remove_reference in the same place for the same purpose.

这篇关于为什么在C ++ 0x右值引用的正向定义中使用标识?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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