开发者

C++: Vector3 type "wall"?

Say I have:

class Vector3 {
  float x, y, z;
  ... bunch of cuntions ..
  static operator+(const Vector3&, const Vector3);
};

Now, suppose I want to have classes:

Position, Velocity, 

that are exactly like Vector3 (basically, I want

typedef Vector3 Position;
typedef Vector3 Velocity;

Except, given:

Position position;
Vect开发者_开发百科or3 vector3;
Velocity velocity;

I want to make sure the following can't happen:

position + vector3;
vector3 + velocity;
velocity + position;

What is the best way to achieve this?


I would recommend something like this:

template<typename tag>
class Vector3 {
  float x, y, z;
  ... bunch of functions ..
  static operator+(const Vector3&, const Vector3);
};

struct position_tag {};
struct velocity_tag {};
typedef Vector3<position_tag> Position;
typedef Vector3<velocity_tag> Velocity;

See here for a more elaborate example: Boost MPL


Instead of using typedef, you can derive Position & Velocity from Vector3. Then remove operator+ from Vector3, and define it in Position & Velocity.

class Vector3 {
  float x, y, z;
  ... bunch of cuntions ..
};

class Position : public Vector3 {
  static Position operator+(const Position&, const Position&);
}

class Velocity : public Vector3 {
  static Velocity operator+(const Velocity&, const Velocity&);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜