C++ Logo

std-proposals

Advanced search

[std-proposals] Typedef

From: Karafiát, László <laszlo_at_[hidden]>
Date: Fri, 16 Aug 2024 13:33:23 +0200
Dear fellows,

In practice we have a good many times scalar (simple/unstructured) type
of objects with pronounced domain specific behaviours. I propose a
rather simple kind of type/class definition for these.

1. A typedef extension like this would suffice

     // Values in radians in the range [-π,π)
     typedef float Angle // as before
     { // NEW
       float degrees() { return *this * 180f / π; } // NEW
       bool isAcute() { return abs(*this) < /2f; } // NEW
         :
         .
     }; // NEW


     :
     .

     Angle α = π/6.f, // as before
           β = π/4.f;

     if (α == β) println(...);

     if (α.isAcute()) println(...); // NEW

With other words,
   1.a The new typedef could have a body with class-like definitions
(operators, properties, constructors, *this etc).

   1.b Using the object name would suffice to reference its value as
with other typedefs, no extra .fieldname is necessary as it would in
case of traditional classes. This brings significantly enhanced
readability. The functions can be invoked like in case of classes - no
syntactical news here (i.e. no confusion either).

2. It would be nice to have sg. similar for enums as well (being they
scalar types too).

     enum class CompassDir : short
     {
       None = -1,
       East, NorthEast, North, NorthWest,
       West, SouthWest, South, SouthEast;

       // Here come the tidings ====================================
       CompassDir (const Angle α) // A constructor
       { (CompassDir) (short((α.degrees()+382.5f)/45f) & 7); }

       bool isCardinal() { return (*this & 1) == 0; }
       CompassDir opposite() { return (CompassDir) (*this ^ 4); }
         :
         .
     };

     :
     .

     Angle α = π/6.f; // as before
     CompassDir cd = CompassDir(α); // NEW


   2.a Eventually this could also be introduced as

     typedef enum CompassDir : short
     {
         ... // as above
     };

to stress the scalar quality of enums.

When teaching the language it would be a good start to introduce these
kind of type definitions before talking about classes/structs (tuples).


Best regards
László Karafiát

Received on 2024-08-16 11:33:19