Mc Missile
Mc Missile

Reputation: 735

Typecasting custom structs

I have two structs defining a point and a vector in a given frame.

struct point3D
{
  float x;
  float y;
  float z;
};
struct vector3D
{
  float x;
  float y;
  float z;
};

The reason they are defined as two different structs is because there are other functions that treat a point(point3D) differently to a vector (vector3D) tho they have the same type of member variables

I was wondering if there is a way to typecast one of them into another say for example:

point3D variable1;
vector3D variable2;
variable2=(vector3D)variable1;

Upvotes: 3

Views: 789

Answers (2)

Red.Wave
Red.Wave

Reputation: 4249

I will give you the knife, even though I am sure you are not a surgean. Karsten recommended - in a comment - to derive point from vector. If that is not fine, go ahead and cheat: the proper casting operator is reinterpret_cast.

point3D variable1; 
vector3D variable2;
variable2=reinterpret_cast<vector3D&>(variable1);

but that was C++. If a C style cast is what you need, then a pointer cast is the way:

variable2=*(vector3D*)(void*)&variable1;

Either of the two solutions above are discouraged. A redesign I would consider, if in your shoes I were.

Upvotes: 0

Tyker
Tyker

Reputation: 3047

you can do this

struct vector3D
{
  float x;
  float y;
  float z;
};

struct point3D
{
  float x;
  float y;
  float z;
  explicit operator vector3D() {
    return {x, y, z};
  }
};

Upvotes: 3

Related Questions