mercredi 26 août 2015

C++11: Range-based for loop over range described by templated iterators

In my C++03 code, I have a lot of functions that look like this:

class A {
public:
    template <Iterator>
    void doSomethingWithObjects(Iterator begin, Iterator end) {
        for (Iterator point = begin; point != end; point++) {
            mInternal.doSomething(*point);
        }
    }
private:
    DataStructure mInternal;
};

I'm trying to use C++11's features as much as possible in new code, in particular the range-based for loop. My question is, how would I do this with templated iterators? Is there a magic C++ structure that takes two templated iterator types, and turns them into a range expression? In other words, I'm looking for something like this:

class A {
public:
    template <Iterator>
    void doSomethingWithObjects(Iterator begin, Iterator end) {
        static_assert(std::is_same<Point, typename std::decay<Iterator>::type>::value, "wrong type mate!"); // extra credit
        for (auto&& point : std::magic(begin, end)) {
            mInternal.doSomething(point);
        }
    }
private:
    DataStructure mInternal;
};

If there is a new, preferred ways to do this kind of "add a number of objects to this structure" in C++11, I'm all ears, too.

Aucun commentaire:

Enregistrer un commentaire