Wednesday, May 14, 2014

Building custom iterators

Once one realizes that STL algorithms open the doors for expression, readability, maintenance and reusability, he wants to have it for the classes he creates.

Of course, you shouldn't expose the internals of your class, so you need a way to offer exploration of your object's data, without exposing implementation details, like the underlying data structures:

The quick-and-dirty way is to  provide algorithms for your class.

class Polygon {
        vector<Point> vertices;
    public:
        template <class Func>
        Func for_each_vertex ( Func f );  // access by vertex

        template <class Func>
        Func for_each_edge ( Func f );  // access by edge
};


However, this gives you limited expression. You soon have to write versions for find(), find_if(), copy(), copy_if(), transform(), count_if(), all_of(), any_of(), none_of(), and you end up replicating part of STL algorithms for each class, for each access type (by vertex, by edge).

Read this article, to see how you can implement this interface:

class Polygon {
        vector<Point> vertices;
    public:
        vertex_iterator begin_vertex();
        vertex_iterator end_vertex();

        edge_iterator begin_edge();
        edge_iterator end_edge();
};

Monday, May 5, 2014

inline, static, extern functions and namespaces

How safe do you think it is to write this piece of code in your .cpp file ?


file.cpp
struct Point {
    double *px;
    double *py;

    Point (double x, double y) {
        px = new double(x);
        py = new double(y);
    }
    ~Point() {
        delete x;
        delete y;
    }

    // other members ...
};

Read more why this is the most dangerous piece of code you can write in your .cpp, and it is more likely to be spotted after releasing the project...