17

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

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

随着右值引用的引入,人们可以从完美转发中受益,但通常会删除 const 限定符,例如:

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

除了文档之外,是否有一种描述 function2 不会改变其输入的好方法?

4

2 回答 2

29
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 &,每个人都会明白。这是一个简单易懂的成语。

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

于 2013-06-09T01:19:31.000 回答
9

你可以这样说:

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 {};

这样,只有当通用引用是常量引用(so T = U const &)或右值引用(soT不是引用)时,模板才可用。


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

于 2013-06-09T01:12:02.800 回答