C++ 语义类型包装

标签 c++ overloading

我有一个数据类型,例如 class Vector3。现在我需要创建几个类,它们具有与 Vector3 相同的接口(interface),但具有更高级别的语义(例如:PositionVelocity)。使用 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 /* ... */ }
    };

如果你喜欢冒险,你可以去掉 explicit 关键字,或者启用隐式转换运算符。这将具有能够启用混杂 运算符解析的“好处”,如下所示:

 Position pos;
 Direction dir;
 Generic gen;

 dir = gen + pos; // you see why I call it 'promiscuous'?

我建议(而不是)为这种情况定义显式运算符(免费功能:)

 Position operator+(const Position& v, const Translation& d) { /* .... */ }

这样你的类模型就反射(reflect)了类的语义。

C++0x would possibly contain things to enable explicit conversion operators , IIRC:

In the case of converting constructors, you can disable implicit conversions by declaring the constructor as explicit The N1592 proposal 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

关于C++ 语义类型包装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6383032/

相关文章:

c++ - 使用 unique_ptr 和原始指针重载全局函数

c++ - C++ 中的每个表达式是否都具有非指针类型,如非引用类型

c++ - 对递归数独回溯函数的模糊调用。

C++ 基于整数对返回字符串

c++ - Vector 只获取无重复元素

C++继承方法调用基类的方法而不是重载方法

java - 编译器似乎混淆了重载方法的两个版本。为什么?

c++ - 通过 LevelDB 将 Protocol Buffer 序列化数据从 C++ 传递到 Python

c++ - 对非模板类型使用通用引用?

c++ - 为点坐标创建类