Origin - permanent or new type?

I wrote the Point class (in 3d space) and wondered what would be the best way to create a starting point. Here is the base class (taken from Andy’s example, just in case someone wondered what the main implementation was):

 struct Point { constexpr Point(double x_, double y_, double z_) : x(x_), y(y_), z(z_) { } double x; double y; double z; }; 

The first way to have the origin would be to define a constexpr variable:

 constexpr Point origin = { 0.0, 0.0, 0.0 }; 

The second would be to define a new type and overload algorithms so that they can benefit from optimizations when computing from the beginning (let's say I wrote a constexpr constructor for Point ):

 struct Origin: public Point { constexpr Origin(): Point(0.0, 0.0, 0.0) {} }; constexpr Origin origin; 

While the first method seems simpler and less error prone, I would like to know if the second one looks like a good idea, and if I have some pitfalls that I have not seen.

EDIT: Thinking about link libraries, I noticed that CGAL used something like this:

 class Origin {}; const Origin ORIGIN; 
+4
source share
1 answer

While the first method seems simpler and less error prone, I would like to know if the second one looks like a good idea, and if I have some pitfalls that I have not seen.

I think that the inheritance design is conceptually wrong: you don’t want to introduce a new type here, and the origin is conditionally an instance (a very special instance, but still an instance) of the Point class not a specialization of this type.

I would prefer to add a static constexpr member constexpr called origin() here:

 struct Point { constexpr Point(double x_, double y_, double z_) : x(x_), y(y_), z(z_) { } constexpr static Point origin() { return {0, 0, 0}; } double x; double y; double z; }; 

Then you can use it as follows:

 int main() { constexpr Point o = Point::origin(); } 

Alternatively, you can add a static data element of type Point called origin , rather than a static function called origin() . Which one to choose is basically a matter of taste.

+6
source

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


All Articles