opCmp with and without const

berni44 dlang at d-ecke.de
Fri Dec 6 07:03:45 UTC 2019


In std.typecons, in Tuple there are two opCmp functions, that are 
almost identical; they only differ by one being const and the 
other not:

         int opCmp(R)(R rhs)
         if (areCompatibleTuples!(typeof(this), R, "<"))
         {
             static foreach (i; 0 .. Types.length)
             {
                 if (field[i] != rhs.field[i])
                 {
                     return field[i] < rhs.field[i] ? -1 : 1;
                 }
             }
             return 0;
         }

         int opCmp(R)(R rhs) const
         if (areCompatibleTuples!(typeof(this), R, "<"))
         {
             static foreach (i; 0 .. Types.length)
             {
                 if (field[i] != rhs.field[i])
                 {
                     return field[i] < rhs.field[i] ? -1 : 1;
                 }
             }
             return 0;
         }


What is the reason for having this? (I guess, that it's because 
the function may indirectly call opCmp of other types which may 
or may not be const.)

My real question is: Can this code duplication be avoided 
somehow? (I ask, because I've got a PR running, which increases 
the size of these functions and it doesn't feel good to have two 
long, almost identical functions.)


More information about the Digitalmars-d-learn mailing list