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

前端 未结 3 757

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

3条回答
  •  隐瞒了意图╮
    2020-12-06 04:31

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

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

    template 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())
    

提交回复
热议问题