微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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 举报,一经查实,本站将立刻删除。

相关推荐