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:
In the case of converting constructors,you can disable implicit conversions by declaring the constructor as explicit The 07001 stretches the semantics of this keyword to all conversion operators. A conversion operator declared explicit will not perform an implicit conversion. Instead,the programmer will have to call it explicitly
原文地址:https://www.jb51.cc/c/110495.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。