[英]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_t
为const
)是错误的,因为您的 function 应该能够在非const
范围内运行。
Since c++17 , you can use std::as_const
every time you deference your iterator:由于c++17 ,您可以在每次尊重迭代器时使用
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 c++17 , it's pretty trivial to implement your own version of std::as_const
.注意:如果您无权访问c++17 ,那么实现您自己的
std::as_const
版本非常简单。 Just make sure you declare it outside of namespace std
.只要确保你在命名空间
std
之外声明它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.