简体   繁体   English

使用迭代器的泛型函数中的 const 正确性

[英]Const correctness in generic functions using iterators

I want to write a generic functions that takes in a sequence, while guaranteeing to not alter said sequence.我想编写一个接受序列的通用函数,同时保证不改变所述序列。

template<typename ConstInputIter, typename OutputIter>
OutputIter f(ConstInputIter begin, ConstInputIter end, OutputIter out)
{
  InputIter iter = begin;
  do
  {
    *out++ = some_operation(*iter);
  }while(iter!=end);
  return out;
}

Yet the above example still would take any type as ConstInputIterator , not just const ones.然而,上面的示例仍然可以将任何类型作为ConstInputIterator ,而不仅仅是const类型。 So far, the notion towards being const in it is nominal.到目前为止,在其中成为const的概念是名义上的。

How do I declare the sequence given will not be altered by this function?我如何声明这个 function 不会改变给定的序列?

Even in C++20, there is no generic way to coerce an iterator over a non- const T into an iterator over a T const .即使在 C++20 中,也没有通用方法将非const T上的迭代器强制转换为T const上的迭代器。 Particular iterators may have a mechanism to do that, and you can use std::cbegin/cend for ranges to get const iterators.特定的迭代器可能具有执行此操作的机制,您可以使用std::cbegin/cend获取范围以获取 const 迭代器。 But given only an iterator, you are at the mercy of what the user provides.但是给定一个迭代器,您将受制于用户提供的内容。

Applying a C++20 constraint (requiring iter_value_t to be const ) is the wrong thing, as your function should be able to operate on a non- const range.应用 C++20 约束(要求iter_value_tconst )是错误的,因为您的 function 应该能够在非const范围内运行。

Since , you can use std::as_const every time you deference your iterator:由于 ,您可以在每次尊重迭代器时使用std::as_const

// ...
*out++ = some_operation(std::as_const(*iter));
// ...

This makes sure you never access the elements of the underlying container through a non- const l-value reference.这确保您永远不会通过非const左值引用访问底层容器的元素。

Note: if you don't have access to , it's pretty trivial to implement your own version of std::as_const .注意:如果您无权访问 ,那么实现您自己的std::as_const版本非常简单。 Just make sure you declare it outside of namespace std .只要确保你在命名空间std之外声明它。

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

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