C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Typedef

From: Tiago Freire <tmiguelf_at_[hidden]>
Date: Fri, 16 Aug 2024 13:17:48 +0000
Have you considered creating a utility class which defines the cast functions? And how would that solution compare to this?
________________________________
From: Std-Proposals <std-proposals-bounces_at_[hidden]> on behalf of Karafi¨¢t, L¨¢szl¨® via Std-Proposals <std-proposals_at_[hidden]>
Sent: Friday, August 16, 2024 1:33:23 PM
To: std-proposals_at_[hidden] <std-proposals_at_lists.isocpp.org>
Cc: Karafi¨¢t, L¨¢szl¨® <laszlo_at_karafiat.name>
Subject: [std-proposals] Typedef


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

--
Std-Proposals mailing list
Std-Proposals_at_[hidden]p.org
https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2024-08-16 13:17:54