c ++ rvalue引用和const限定符

a.l*_*ram 17 c++ c++11

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

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

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

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

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

How*_*ant 29

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

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

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

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

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

你可以这样做:

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

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

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


Ker*_* SB 9

你可以这样说:

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

在哪里你有类似的东西:

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

template <typename U> struct immutable<U const &>
: std::true_type {};
Run Code Online (Sandbox Code Playgroud)

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


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