C ++: Vector3 of the "wall" type?

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, 

which exactly match Vector3 (basically I want

 typedef Vector3 Position; typedef Vector3 Velocity; 

Except if:

 Position position; Vector3 vector3; Velocity velocity; 

I want to make sure the following cannot happen:

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

What is the best way to achieve this?

+4
source share
2 answers

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 detailed example: Boost MPL

+3
source

Instead of using typedef, you can get Position and Velocity from Vector3. Then remove the + operator from Vector3 and define it in position and speed.

 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&); } 
+1
source

Source: https://habr.com/ru/post/1304211/


All Articles