C语义类型包装
我有一个数据类型,例如类Vector3.现在我需要创建几个与Vector3具有相同接口的类,但具有更高级别的语义(例如:Position,Velocity).使用typedef是不够的,因为我需要这些类型是不同的,以便它们可以用于重载.在C 0x中我可能使用构造函数继承:
struct Position: public Vector3 { using Vector3::Vector3; }; 这有什么问题吗?有没有更好的方法呢?是否可以在不使用C 0x功能的情况下执行此操作而不必显式写入所有Vector3构造函数? 解决方法
考虑使用标签结构
struct tagPosition {}; struct tagDirection {}; struct tagGeneric {}; namespace detail { template <typename Tag=tagGeneric> class Vector3 { // business as usual }; } typedef detail::Vector3<tagPosition> Position; typedef detail::Vector3<tagDirection> Direction; typedef detail::Vector3<tagGeneric> Vector3; 对于奖励积分,有转换运算符/构造函数: template <typename Tag=tagGeneric> class Vector3 { template <typename OtherTag> explicit Vector3(const Vector3<OtherTag>& rhs) { /* ... */ } // template <typename OtherTag> // operator Vector3<OtherTag>() const { return /* ... */ } }; 如果您喜欢危险地生活,可以删除显式关键字,或启用隐式转换运算符.这将具有能够启用混杂的操作符解决方案的“好处”,如下所示: Position pos; Direction dir; Generic gen; dir = gen + pos; // you see why I call it 'promiscuous'? 我建议(相反)为这样的情况定义显式运算符(自由函数:) Position operator+(const Position& v,const Translation& d) { /* .... */ } 这样,您的类模型反映了类的语义. II000,C++0x would possibly contain things to enable explicit conversion operators:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |