C++ Strong Duck

Not a Duck. Amazing how similar. Obviously we need Duck Strong Type.
Not a Duck. But, amazingly similar. Obviously we need Duck Strong Type, to avoid mistakes.

I admit. C++ Strong Duck , is a click bait title. Perhaps.

Please first make a slight detour into the direction of “Strong Type by Struct“.

“Just make everything to be a class”. Primordial C++ idea. But, I don’t care if it is. It works. If used but not overused. There is no complex C++ lib behind. Almost nothing.  Just the agreement.

Make every “strong type” as one struct, with a single member named ‘v’. Name of the struct is the strong type name. Type of the v is defined by you.

Let the code speak.

#define STRONG(N,T) struct N final { T v; }

This is my minuscule macro, that works for me. We do not want to mix kilograms and millimeters. So lets make them as strong types.

   // measurement units
    STRONG(Kg, double);
    STRONG(Mm, double);

And now we have some creatures to manage. We use the same ridiculously simple macro to produce much cleaner code.

 // attributes of a specimen
    STRONG(Height, Mm ) ;
    STRONG(Weight, Kg ) ;

Ah OK, here is the first duck flying in. Lets take care of it.

   // we will call it 'duffy'
   //  same as every other creature, duffy can not change (morph)
   // into some other Duck, even if they are both Duck's 
   // ditto ...
    constexpr struct StrongDuck final {
        mutable Height height;
        mutable Weight weight;
    } duffy { {4.2},{430.23} } ;

Duffy is immutable, but it has gained in weight

duffy.weight = {4.552 };

There are no methods, here, one can indeed mistake height for weight when giving them values, but everybody knows what to do about that.

The point is we have described a Duck as a strong type. Much (much) better than:

   struct Duck {  double h; double w ; }

One can say: “Strong Duck” typing indeed :)