繁体   English   中英

c ++ rvalue引用和const限定符

[英]c++ rvalue reference and const qualifier

const限定的许多好处之一是使API更容易理解,例如:

template<typename T> int function1(T const& in);
// clearly, the input won’t change through function1

通过引入rvalue引用,可以从完美转发中受益,但通常会删除const限定符,例如:

template<typename T> int function2(T&& in);
// can explicitly forward the input if it's an rvalue

除了文档之外,还有一种很好的方法来描述function2不会改变它的输入吗?

 template<typename T> int function2(T&& in); // can explicitly forward the input if it's an rvalue 

除了文档之外,还有一种很好的方法来描述function2不会改变它的输入吗?

是。 坚持使用C ++ 03解决方案:

template<typename T> int function1(T const& in);
// clearly, the input won’t change through function1

完美转发的好处是你不想假设某些东西是const或非const ,左值或右值。 如果你想强制某些东西没有被修改(即它是const ),那么通过添加const明确地这样说。

你可以这样做:

template<typename T> int function1(T const&& in);
// clearly, the input won’t change through function1

但是,阅读代码的每个人都会想知道为什么你使用了右值引用。 并且function1将停止接受左值。 只需使用const &而不是每个人都会理解。 这是一个简单易懂的习语。

你不想完美前进。 你想强制执行不变性。

你可以这样说:

template <typename T>
typename std::enable_if<immutable<T>::value, int>::type
function(T && in)
{
   // ...
}

在哪里你有类似的东西:

template <typename T> struct immutable
: std::integral_constant<bool, !std::is_reference<T>::value> {};

template <typename U> struct immutable<U const &>
: std::true_type {};

这样,只有当通用引用是const引用(因此T = U const & )或rvalue-reference(因此T不是引用)时,模板才可用。


也就是说,如果参数不会被改变,你可以使用T const &并完成它,因为从可变绑定到临时值没有任何东西可以获得。

暂无
暂无

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

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