Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/144.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c++;右值引用和常量限定符_C++_C++11 - Fatal编程技术网

C++ c++;右值引用和常量限定符

C++ c++;右值引用和常量限定符,c++,c++11,C++,C++11,const资格认证的诸多好处之一是使API更易于理解,例如: template<typename T> int function1(T const& in); // clearly, the input won’t change through function1 template<typename T> int function2(T&& in); // can explicitly forward the input if it's an r

const资格认证的诸多好处之一是使API更易于理解,例如:

template<typename T> int function1(T const& in);
// clearly, the input won’t change through function1
template<typename T> int function2(T&& in);
// can explicitly forward the input if it's an rvalue
模板int函数1(T const&in);
//显然,输入不会通过功能1改变
通过引入右值引用,可以从完美转发中获益,但通常会删除常量限定符,例如:

template<typename T> int function1(T const& in);
// clearly, the input won’t change through function1
template<typename T> int function2(T&& in);
// can explicitly forward the input if it's an rvalue
模板int函数2(T&&in);
//如果输入为右值,则可以显式转发该输入
除了文档之外,是否有一种好的方法来描述function2不会更改其输入?

您可以这样说:

template <typename T>
typename std::enable_if<immutable<T>::value, int>::type
function(T && in)
{
   // ...
}
模板
typename std::enable_if::type
函数(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 {};
模板结构不可变
:std::积分_常数{};
模板结构不可变
:std::true_type{};
这样,只有当通用引用是常量引用(so
T=U const&
)或右值引用(so
T
不是引用)时,模板才可用


这就是说,如果参数不改变,您可以使用
T const&
并完成它,因为可变绑定到临时值没有任何好处

然而,阅读您的代码的每个人都会想知道您为什么使用右值引用。而
function1
将停止接受左值。只需使用
const&
,大家就会明白。这是一个简单易懂的成语


你不想完全向前。您希望强制执行不变性。

如果您只是将参数转发给其他人,您关心的是什么是或不是
const
?你让他们来处理。
template<typename T> int function1(T const&& in);
// clearly, the input won’t change through function1