Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

c++ - forcing use of cbegin()/cend() in range-based for

This question refers to:

When should I use the new ranged-for and can I combine it with the new cbegin/cend?

Based on that question, to force the use of cbegin() and cend(), one needs to do, for example:

for (auto& v: const_cast<decltype(container) const>(container))

That's a lot of boilerplate code for a construct that was supposed to eliminate it. Is there some more compact way to do it? The reason for my question is, that an implicitly shared container might take my use of begin() as a clue to detach itself.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Update: std::as_const will be in C++17, in the <utility> header.

Prior to C++17, there's no built-in syntax for it; however, you can easily write a convenience wrapper:

template<typename T> constexpr const T &as_const(T &t) noexcept { return t; }
for (auto &v: as_const(container))

Note that this calls begin() const rather than cbegin() specifically; the Standard container general requirements specify that cbegin() and begin() const behave identically.

If your container treats non-const iteration specially, it might make sense for it itself to have a member function:

const Container &crange() const noexcept { return *this; }
for (auto &v: container.crange())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...