EvilsInterrupt
@EvilsInterrupt
System programming, Reversing Engineering, C++

Как добавить поддержку range-based цикла в свой класс?

Привет, всем!

Прошу знающих и опытных в C++11 помочь.

Написал свой первый "Hello World" чтобы научиться добавлять в свои типы поддержку for-each цикла. Вот код:

#include <iostream>
#include <list>


struct Foo
{
    int f1;
    double f2;
    short f3;
};

class RangeBasedLoopExample
{
public:
    typedef std::list<Foo>::iterator iterator_t;
    typedef std::list<Foo>::const_iterator const_iterator_t;

public:
    RangeBasedLoopExample() {
        Foo foo1 = {1, 2.5, 3};
        Foo foo2 = {2, 3.6, 4};
        fooList.push_back(foo1);
        fooList.push_back(foo2);
    }

    iterator_t begin() {
        std::cout << "[1] - RangeBasedLoopExample::begin()\n";
        return fooList.begin();
    }

    iterator_t end() {
        std::cout << "[2] - RangeBasedLoopExample::end()\n";
        return fooList.end();
    }

    const_iterator_t begin() const {
        std::cout << "[3] - RangeBasedLoopExample::begin() const\n";
        return fooList.begin();
    }

    const_iterator_t end() const {
        std::cout << "[4] - RangeBasedLoopExample::end() const\n";
        return fooList.end();
    }

    const_iterator_t cbegin() {
        std::cout << "[5] - RangeBasedLoopExample::cbegin()\n";
        return fooList.cbegin();
    }

    const_iterator_t cend() {
        std::cout << "[6] - RangeBasedLoopExample::cend()\n";
        return fooList.cend();
    }

private:
    std::list<Foo> fooList;
};


void print1(RangeBasedLoopExample& b)
{
    for (const auto& foo : b)
        std::cout << foo.f1 << ';' << foo.f2 << ';' << foo.f3 << '\n';
}

void print2(const RangeBasedLoopExample& b)
{
    for (const auto& foo : b)
        std::cout << foo.f1 << ';' << foo.f2 << ';' << foo.f3 << '\n';
}

int main(int argc, char* argv[])
{
    print1(RangeBasedLoopExample());
    print2(RangeBasedLoopExample());
    return 0;
}


Однако пока не пойму, когда и при каких условиях будет вызваны cbegin() и cend() с какой целью они существуют в std::list и др. типах? Когда их надо добавлять в свои типы?
  • Вопрос задан
  • 2496 просмотров
Решения вопроса 1
jcmvbkbc
@jcmvbkbc
"I'm here to consult you" © Dogbert
iterator_t
const_iterator_t

Суффикс _t зарезервирован, лучше его не использовать в своём коде.

const_iterator_t cbegin()
const_iterator_t cend()

В стандартных контейнерах эти методы -- const.

при каких условиях будет вызваны cbegin() и cend()

Думаю, что только явно программистом, руками.

с какой целью они существуют в std::list и др. типах

Чтобы можно было легко получить константный итератор из неконстантного контейнера.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы