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