简体   繁体   中英

Conversion between types

This is a question about class design. I am confuse about how the compiler will deal with those two classes. As a object oriented language C++ need to optimize le layer of abstraction or type abstraction to be efficient. An example that I can think about are iterator. They are a totaly different type than a pointer and yet the compiler can optimise and for example in a for loop be as efficient as a pointer.

What I am concern about is how to make those two classes as efficient if they would be only one. The two classes are the mathematic representation of a Point3 and a Vector3.

Operation on Point3 are really limited but in mathematic we can make a Vector3 out of a Point3 by substracting it from the Origin. we can also do the oposite by considering the end of the Vector3 as a Point3.

An example of this would be to scale a Point3.

Point3<float> positionStart;
Vector3<float> scale;
Point3<float> positionEnd;

positionEnd = scale * positionStart;

This should convert the positionStart Point3 to a Vector3, do the multiplication and then take the end point of the temporary Vector3 to assign it to the positionEnd .

How do we code this efficiently in C++ so that those conversion don't actually happen. Because in the end Point3 and Vector3 are represented by 3 floats. At runtime it should mather if it was a Point3 or a Vector3 but compiler should care about the type not the processor.

I hope this is clear I'll try to explain better my confusion if not.

thanks

** Update ** To focus a bit more the question, this can be done with conversion constructors or conversion. operators. The internal are actually the same. Will the compiler be able to see trough and optimize out, I guess by inlining, those constructors and conversion operators.

The simplest way to do this would be to have the point coordinates be stored internally as a vector. Since I have no idea what operator* would do, I'll show it with operator+ where the sematics is clear (note however that this is untested code):

template<typename Field> class Point
{
public:
  Point& operator+=(Vector<Field> const& v);
  // the rest of the Point interface
private:
  Vector<Field> position; // holds the vector from the origin to this point
};

template<typename Field>
 inline Point<Field>::operator+=(Vector<Field> const& v)
{
  position += v;
}

template<typename Field>
 inline Point<Field> operator+(Point<Field> p, Vector<Field> const& v)
{
  return p += v;
}

Now, p += v will be optimized to the exact code that p.position += v would compile to if position were not private. So ultimately you have only a vector addition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM