我目前正在编写一个小型通用库,用于在场景中放置对象。应根据对象内容的边界框来确定对象的排列。该课程目前看起来像这样:
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;
};
现在,要构造对象,我们需要知道边界框。当然,它取决于内容的类型T
,并且计算起来可能相当复杂(即文本)。
我的想法是,用户应该提供自己的Measurer
,为自己的内容执行此计算。然后可以通过以下方式创建对象:
template <class T, class Measurer>
Object create_label(const T& value, Measurer op)
{
return Object(value, op(value));
}
这种方法是否应该以某种方式纳入Object
类(类似政策)?我在想与STL中的分配器类似的东西。是否存在针对此类问题的通用设计模式,您将如何编写这样的类?
此外,构造函数Object(const T& content, const Rect& bounding_box)
是否应标记为protected
,以便用户指向create_label
方法?
答案 0 :(得分:1)
为什么不添加另一个带测量器的构造函数?
template<class T>
class Object {
public:
Object() = default;
Object(const T& content, const Rect& bounding_box)
: _content(content)
, _bounding_box(bounding_box) {}
template<class Measurer>
Object(const T& content, Measurer op) : _content(content), _bounding_box(op(content)){}
private:
T _content;
Rect _bounding_box;
};