jeudi 27 août 2015

c++ generic builder method for object with complex constructor

I'm currently writing a small generic library for placing objects in a scene. The arrangement of the objects should be decided depending on the bounding box of the contents of the object. The class currently looks something like this:

template<class T>
class Object {
  public:
    Object() = default;
    Object(const T& content, const Rect& bounding_box)
        : _content(content)
        , _bounding_box(bounding_box) {}
  private:
    T    _content;
    Rect _bounding_box;
};

Now, to construct the object we need to know the bounding box. Naturally it depends on the type T of the contents and might be quite complex to calculate (i.e. text).

My idea was that the user should supply its own Measurer which performs this calculation for his own content. An object could then be created by:

template <class T, class Measurer>
Object create_label(const T& value, Measurer op)
{
    return Object(value, op(value));
}

Should this method be somehow incorporated into the Object class (something like a policy)? I was thinking something similar to allocators in the STL. Is there a generic design pattern for this kind of problem and how would you write such a class?

Also, should the constructor Object(const T& content, const Rect& bounding_box) be marked as protected, so that the user is pointed to the create_label method?

Aucun commentaire:

Enregistrer un commentaire