<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<style type="text/css">
pre {margin-left:20pt; }
pre > i {
  font-family: "OCR A Extended", "Consolas", "Lucida Console", monospace;
  font-style:italic;
}
code > i {
  font-family: "OCR A Extended", "Consolas", "Lucida Console", monospace;
  font-style:italic;
}
pre > em {
  font-family: "OCR A Extended", "Consolas", "Lucida Console", monospace;
  font-style:italic;
}
code > em {
  font-family: "OCR A Extended", "Consolas", "Lucida Console", monospace;
  font-style:italic;
}
body { color: #000000; background-color: #FFFFFF; }
del { text-decoration: line-through; color: #8B0040; }
ins { text-decoration: underline; color: #005100; }

p.example { margin-left: 2em; }
pre.example { margin-left: 2em; }
div.example { margin-left: 2em; }

code.extract { background-color: #F5F6A2; }
pre.extract { margin-left: 2em; background-color: #F5F6A2;
  border: 1px solid #E1E28E; }

p.function { }
.attribute { margin-left: 2em; }
.attribute dt { float: left; font-style: italic;
  padding-right: 1ex; }
.attribute dd { margin-left: 0em; }

blockquote.std { color: #000000; background-color: #F1F1F1;
  border: 1px solid #D1D1D1;
  padding-left: 0.5em; padding-right: 0.5em; }
blockquote.stddel { text-decoration: line-through;
  color: #000000; background-color: #FFEBFF;
  border: 1px solid #ECD7EC;
  padding-left: 0.5empadding-right: 0.5em; ; }

blockquote.stdins { text-decoration: underline;
  color: #000000; background-color: #C8FFC8;
  border: 1px solid #B3EBB3; padding: 0.5em; }

table.header { border: 0px; border-spacing: 0;
  margin-left: 0px; font-style: normal; }

table { border: 1px solid black; border-spacing: 0px;
  margin-left: auto; margin-right: auto; }
th { text-align: left; vertical-align: top;
  padding-left: 0.4em; border: none; 
  padding-right: 0.4em; border: none; }
td { text-align: left; vertical-align: top;
  padding-left: 0.4em; border: none;
  padding-right: 0.4em; border: none; }
</style>

<title>Remove 'CommonReference' requirement from 'StrictWeakOrdering'</title>
</head>

<body>

<table class="header"><tbody>
  <tr>
    <th>Document number:&nbsp;&nbsp;</th><th> </th><td>P1248R1</td>
  </tr>
  <tr>
    <th>Date:&nbsp;&nbsp;</th><th> </th><td>2018-11-04</td>
  </tr>
  <tr>
    <th>Audience:&nbsp;&nbsp;</th><th> </th><td>Library Evolution Working Group</td>
  </tr>
  <tr>
    <th>Reply-to:&nbsp;&nbsp;</th><th> </th><td><address>Tomasz Kamiński &lt;tomaszkam at gmail dot com&gt;</address></td>
  </tr>
</tbody></table>

<h1><a name="title">Remove <code>CommonReference</code> requirement from <code>StrictWeakOrdering</code> (a.k.a Fixing <code>Relation</code>s)</a></h1>

<h2><a name="intro">1. Introduction</a></h2>

<p>This paper proposes changing the <code>Relation</code> and related concepts, to achieve following goals:</p>
<ul>
  <li><em>zero overhead</em>: uses of range version of standard algorithm shall not be less effective than hand written code,
                              especially it shall not be less effective than STL1 counterparts,</li>
  <li><em>generality</em>: concepts should be usable both in case of algorithms and containers, they should map to the underlying 
                           mathematical concepts and avoid imposing additional requirement,</li>
  <li><em>soundness</em>: the syntactic requirements of the algorithm should allow to check (in runtime) if supplied object satisfies
                          associated semantic requirement.</li>
</ul>
<p>The secondary goal is to simplify migration to the rangified version of algorithms, however reaching of this goal should 
   not undermine above properties.</p>

<p>This paper argues that the currently specified <code>Relation</code> concept does not achieve above goal, due the additional 
   requirement of <code>CommonReference</code> for types of parameters of callable. As consequence we propose to relax this concept
   (and derived <code>StrictWeakOrdering</code> concept) by removing above requirement.
   [ Note: This affects only requirements on comparators used with STL algorithms, and are not affecting relational operators
     (<code>&lt;</code>, <code>==</code>, ...). ]
</p>

<p>The need for applying this change, was recognized with the inception of the current concept design - similar change is discussed as alternative
   design in Appendix D.2 Cross-type Concepts of <a href="https://wg21.link/n3351">A Concept Design for the STL</a> (The Palo Alto report) paper.<p> 

<!--h2><a name="toc">Table of contents</a></h2-->

<h2><a name="history">2. Revision history</a></h2>

<h3><a name="history.r0">2.1. Revision 0</a></h3>

<p>Initial revision.</p>

<h3><a name="history.r1">2.2. Revision 1</a></h3>

<ul>
  <li>Changed title to be more descriptive</li>
  <li>Properly qualified invocations of <code>equal_range</code> with <code>std::ranges</code> namespaces,
      in situations when range version is discussed.</li>
</ul>

<h2><a name="motivation">3. Motivation and Scope</a></h2>

<p>Family of the standard algorithms related to sorting and operations on sorted sequence (<code>sort</code>, <code>lower_bound</code>, <code>set_intersection</code>, ...)
   are accepting an functor, that is representing a <em>weak ordering</em>. Examples of such ordering, includes relation resulting from a composition of the <em>key function</em>
   that extracts certain part of the object, and the <em>strong ordering</em> relation over extracted part.</p>
   
<p>To illustrate lets us consider following <code>NameLess</code> functor, that is comparing object of <code>Employee</code> by
   comparing only <code>name</code> member:</p>
<pre>struct NameLess
{
   bool operator()(Employee const&amp; lhs, Employee const&amp; rhs) const
   { return lhs.name &lt; rhs.name; }

   bool operator()(Employee const&amp; lhs, std::string_view rhs) const
   { return lhs.name &lt; rhs; }

   bool operator()(std::string_view lhs, Employee const&amp; rhs) const
   { return lhs &lt; rhs.name; }

   bool operator()(std::string_view lhs, std::string_view rhs) const
   { return lhs &lt; rhs; }
};</pre> 

<p>Having above functor, we may sort a vector <code>ve</code> of the <code>Employee</code> object by name:</p>
<pre>std::sort(ve.begin(), ve.end(), NameLess{});</pre>
<p>Now that code can be upgraded to use Ranges:</p>
<pre>std::ranges::sort(ve.begin(), ve.end(), NameLess{});
std::ranges::sort(ve, NameLess{});</pre>
<p>Finally we have an option to provide our <em>key function</em> and <em>strong ordering</em> separately:</p>
<pre>std::ranges::sort(ve, std::less&lt;&gt;{}, &amp;Employee::name);</pre>

<p>Once the vector is sorted, we can use one of the other algorithms to find all employee's with given name
   (i.e. find <em>equivalence class</em> for given value):</p>
<pre>std::equal_range(ve.begin(), ve.end(), "Kowalski"sv, NameLess{});</pre>
<p>However, if we want to migrate the above code to Ranges, by stating:</p>
<pre>std::ranges::equal_range(ve.begin(), ve.end(), "Kowalski"sv, NameLess{});
std::ranges::equal_range(ve, "Kowalski"sv, NameLess{});</pre>
<p>The above invocations will not compile, and we will be forced to rewrite my functor into separate
   projection and comparison:</p>
<pre>std::ranges::equal_range(ve, "Kowalski"sv, std::less&lt;&gt;{}, &amp;Employee::name);</pre>

<p>The above compilation problem is caused by the fact that for the relation to satisfy <code>StrictWeakOrdering&lt;NameLess, Employee, std::string_view&gt;</code>,
   such functor needs to satisfy <code>Relation&lt;NameLess, Employee, std::string_view&gt;</code>, which requires that the types <code>Employee</code> and 
   <code>std::string_view</code> has a common reference (<code>CommonReference&lt;Employee, std::string_view&gt;</code>).</p>

<p>In situation when <em>weak ordering</em> is defined in terms of the composition of the <em>key function</em> and <em>strong ordering</em>, the type
   returned by <em>key function</em> may be unrelated to the actual object type, as we are usually returning a member of that object. This means
   that the user is forced to rewrite they comparators into separate projection and homogeneous functor. 
   This puts an limitation on the implementation freedom for the users, and have negative consequences on expressiveness and runtime performance of the code.</p>

<h3><a name="motivation.cost">3.1. Inefficient abstraction</a></h3>

<p>To illustrate the effect of above limitation, let us consider the following problem: We have a <code>vector&lt;Itinerary&gt;</code>
   representing round-trip flights (to specific destination and back), and we want to find ones that are having departures
   on specific dates.</p>

<p>Firstly we defined the required comparators, <code>LegDepartureDateLess</code> compares departure date on leg, while <code>ItneraryDepartureDatesLess</code>
   compares departures of all legs:</p>
<pre>struct LegDepartureDateLess
{
   bool operator()(Leg const&amp; lhs, Leg const&amp; rhs) const
   { return lhs.departureDate &lt; rhs.departureDate; }

   bool operator()(Leg const&amp; lhs, std::chrono::local_days const&amp; rhs) const
   { return lhs.departureDate &lt; rhs; }

   bool operator()(std::chrono::local_days const&amp; lhs, Leg const&amp; rhs) const
   { return lhs &lt; rhs.departureDate; }

   bool operator()(std::chrono::local_days const&amp; lhs, std::chrono::local_days const&amp; rhs) const
   { return lhs &lt; rhs; }
};

struct ItineraryDepartureDatesLess
{
  bool operator()(Itinerary const&amp; lhs, Itinerary const&amp; rhs) const
  { return less_impl(lhs.legs, rhs.legs); }

  bool operator()(std::vector&lt;std::chrono::local_days&gt; const&amp; lhs, Itinerary const&amp; rhs) const
  { return less_impl(lhs, rhs.legs); }

  bool operator()(Itinerary const&amp; lhs, std::vector&lt;std::chrono::local_days&gt; const&amp; rhs) const
  { return less_impl(lhs.legs, rhs); }

  bool operator()(std::vector&lt;std::chrono::local_days&gt; const&amp; lhs, std::vector&lt;std::chrono::local_days&gt; const&amp; rhs) const
  { return less_impl(lhs, rhs); }
   
private:
  template&lt;typename Sequence1, typename Sequence2&gt;
  bool less_impl(Sequence1 const&amp; lhs, Sequence2 const&amp; rhs) const
  {
    return std::lexicographical_compare(lhs.begin(), lhs.end(),
                                        rhs.begin(), rhs.end(),
                                        LegDepartureDateLess{});
  }
};</pre>

<p>Given above comparison functions, we can sort the vector <code>vi</code> of <code>Itinerary</code>:</p>
<pre>std::sort(vi.begin(), vi.end(), ItineraryDepartureDatesLess{});</pre>
<p>After that we can search for specific set of departure dates (given as vector <code>vd</code>) in the logarithmic time:</p>
<pre>std::equal_range(vi.begin(), vi.end(), vd, ItineraryDepartureDatesLess{});</pre>

<p>If we want to implement the same functionality using the ranges, we can mechanically transform the code sorting elements:</p>
<pre>std::ranges::sort(vi, ItineraryDepartureDatesLess{});</pre>
<p>However such manual transformation will not work if we want to search itineraries departing on specific dates (<code>std::vector&lt;std::chrono::local_days&gt;</code> <code>vd</code>):</p>
<pre>std::ranges::equal_range(vi, vd, ItineraryDepartureDatesLess{});</pre>
<p>will not compile, as (unsuprisingly) there is no common reference between the <code>Itinerary</code> and <code>std::vector&lt;std::chrono::local_days&gt;</code> &mdash;
   it will be ambiguous if <code>std::vector&lt;std::chrono::local_days&gt;</code> meant to represent departure or arrival dates of either
   all legs or all flights constituting given itinerary.</p>

<p>To fix above code, we need to split our comparator into separate projection and relation. In the first attempt we may define projection as follows:</p>
<pre>auto const toDepartureDates = [](Itinerary const&amp; i) -&gt; std::vector&lt;std::chrono::local_days&gt;
{ 
   std::vector&lt;std::chrono::local_days&gt; result(i.legs.size());
   std::ranges::transform(i.legs, result.begin(), &amp;Leg::departureDate);
   return result;
}</pre>

<p>For the comparator, we just need to invoke <code>lexicographical_compare</code> giving following code:</p>
<pre>std::ranges::equal_range(vi, vd,
                         [](auto const&amp; lhs, auto const&amp; rhs) { return std::ranges::lexicographical_compare(lhs, rhs); },
                         toDepartureDates);</pre>
<p>The above code has a major drawback - for each comparison of elements (that is limited by <code><i>O</i>(nlog(n))</code>) a temporary vector is created, leading
   to degradation of the code performance comparing to STL1 example.</p>

<p>This problem can be mitigated by returning a transform view from the <code>toDepartureDates</code> function, to reduce the cost of temporary production:</p>
<pre>auto const toDepartureDatesView = [](Itinerary const&amp; i) { return i.legs | ranges::view::transform(&amp;Leg::departureDate); };</pre>

<p>Above solution does not eliminate the problems caused by common reference requirement, just pushes is one level down.</p>
<pre>std::ranges::equal_range(vi, vd,
                         [](auto const&amp; lhs, auto const&amp; rhs) { return std::ranges::lexicographical_compare(lhs, rhs); },
                         toDepartureDatesView);</pre>
<p>In the above code, provided lambda needs to satisfy <code>StrictWeakOrdering</code> on <code>std::vector&lt;std::chrono::local_days&gt;</code>
   and <code>TransformView</code> (result of <code>toDepartureDateView</code>), which means that common reference between these two
   types needs to exists. This happens to be true for this specific case, as all proposed views are convertible to 
   containers, however if we modify the example to use <code>std::span&lt;std::chrono::local_days&gt;</code>
   instead of <code>std::vector&lt;std::chrono::local_days&gt;</code> the code will again fail to compile,
   as there is no common reference for different views - this specialization also cannot be defined
   by user.</p>

<p>As presented above, the implementation options limitation imposed by requiring a <code>CommonReference</code>
   for orderings, is negatively impacting the performance in the resulting code. 
   Furthermore, this problem will not be fully addressed by the introduction of the views from <a href="https://wg21.link/p0896r2">P0896R2: The One Ranges Proposal</a>
   in C++ standard, as resulting code may fail victim of the same problem &mdash; code fails to compile due lack of `CommonReference` for views.
   In authors opinion, this means that current design of Ranges are breaking zero-overhead principle, which is backbone of
   C++ language - the user is able to implement same functionality in more efficient manner, by simply using older version
   of algorithms, that was not imposing such limitation.</p>

<h3><a name="motivation.sound">3.2. Mathematical soundness</a></h3>

<p>One of the arguments for the introduction of the <code>CommonReference</code> requirement, is that it is <b>required</b>
   to make <code>StrictWeakOrdering</code> mathematically sound. The definition of soundness is a bit subjective, but to counteract the argument,
   the author proposes following approach: The concept is considered to be sound, if it:
   <ul>
     <li>semantic requirements are consistent with the semantic requirements of the underlying mathematical definition,</li>
     <li>syntactic requirements allow above semantic requirement to be verified in code (if necessary at runtime).</li>
   </ul>
</p>

<p>In our case we are interested in the definition of the <em>weak ordering</em> over some domain <em>X</em>. The mathematical
   definition of <em>weak ordering</em> requires following axioms to be true:
   <ul>
     <li><em>irreflexivity</em>: for all <code>x</code> in <em>X</em>: <code>!r(x, x)</code></li>
     <li><em>asymmetry</em>: for all <code>x</code>, <code>y</code> in <em>X</em>: <code>r(x, y)</code> =&gt; <code>!r(y, x)</code></li>
     <li><em>transitivity</em>: for all <code>x</code>, <code>y</code>, <code>z</code> in <em>X</em>: <code>r(x, y) &amp;&amp; r(y, z)</code> =&gt; <code>r(x, z)</code></li>
     <li><em>transitivity of incomparability</em>: for all <code>x</code>, <code>y</code>, <code>z</code> in <em>X</em>: <code>(!r(x, y) &amp;&amp; !r(y, x)) &amp;&amp; (!r(y, z) &amp;&amp; !r(z, y))</code> =&gt; <code>(!r(x, z) &amp;&amp; !r(z, x))</code></li>
   </ul>
</p>

<p>The last requirement is necessary to show that the function <code>eq(x, y)</code> equivalent to <code>!r(x, y) &amp;&amp; !r(y, x)</code> is an equivalence relation,
   i.e. the relation is <em>reflexive</em> (guaranteed by <em>irreflexivity</em> of <code>r</code>),  <em>symmetric</em> (from definition), and <em>transitive</em> (imposed 
   directly by <em>transitivity of incomparability</em> for <code>r</code>). 
   This guarantees that for any <code>x</code>, <code>y</code> in the <em>X</em> only one of following is true:  <code>r(x, y)</code>,  <code>eq(x, y)</code>, <code>r(y, x)</code>,
   where <code>eq</code> is equality relation. 
   That means that <code>r</code> also satisfies definition of <em>weak ordering</em> presented in section "4.2 Total and Weak Orderings" of "Elements of Programming" by Alexander Stepanov and Paul McJones.</p>

<p>To verify if given functor <code>f</code> is strict weak ordering over an domain consisting of objects of type <code>T</code> and of type <code>U</code> 
   (note that domain is just a set of elements, which may be of different type), we will require following invocation to be well-formed:
   <code>f(t, u)</code>, <code>f(u, t)</code>, <code>f(t, t)</code>, <code>f(u, u)</code>, where <code>t</code> is object of type <code>T</code> and <code>u</code>
   of type <code>U</code>.</p>

<p>In summary, neither the semantic requirement of the <em>weak ordering</em> nor the syntactic requirement imposed by them require existence 
   of the common reference (common type) for the objects in the domain. As a consequence the definition of <code>StrictWeakOrdering</code> that
   does not impose <code>CommonReference</code> is equally sound as current definition.</p>

</p>Furthermore, introduction of such additional requirement is limiting the generality of the underlying algorithms (as can work with any <em>weak ordering</em>)
     which is a step against ideas of generic programming.</p>

<h3><a name="motivation.set">3.3. Tailored for algorithms</a></h3>

<p>The current definition of the <code>StrictWeakOrdering</code>, was coined in the context of its usage with newly proposed
   range version of standard algorithms, that accept separate relation and projection arguments. 
   This reasoning, misses other standard library components, that also accepts comparators. This is especially important
   in case of ordered containers (<code>set</code>, <code>map</code>) that are accepting <em>weak ordering</em> as a comparator,
   and were expanded with heterogeneous lookup (<code>is_transparent</code> nested typename).</p>

<p>To illustrate, lets us consider following example, we want to have mapping from the employee's name to the full object, the easiest
   approach would be to use the following map:</p>
<pre>std::map&lt;std::string, Employee&gt; nameMap;</pre>
<p>The drawback of above solution is that the name of the employee is held twice in the structure, once as a key, and once inside the
   object. To mitigate the problem, we could construct a <code>set</code> of <code>Employee</code> that compares only its name, i.e.</p>
<pre>std::set&lt;Employee, NameLess&gt; nameSet;</pre> 
<p>In addition we can allow queering <code>nameSet</code> by actual names, by adding <code>is_transparent</code> nested typedef
   to the <code>NameLess</code> comparator. This solution esentially removes the value duplication.</p>

<p>Note that if the set definition would be changed, so the provided comparator is required to satisfy <code>StrictWeakOrdering</code>
   the code will no longer compile due to <code>CommonReference</code> requirement - this is same situation as in case of
   <code>equal_range</code> example presented in first paragraph.
   As a consequence, constraining the ordered containers with current <code>StrictWeakOrdering</code> concept, will de-facto
   remove functionality of heterogeneous lookup from ordered associative containers.</p> 

<p>Of course, it would be possible to introduce a second concept that would be used for ordered containers, however creating
   multiple concepts representing the same mathematical concept (<em>weak ordering</em>) is against Design Ideas (section 1.3) 
   presented in the <a href="https://wg21.link/n3351">The Palo Alto report</a>: limiting
   number of concepts and providing concept representing general idea in the domain.</p>

<h3><a name="motivation.common_reference">3.4. Hacking <code>common_reference</code></a></h3>

<p>It might be pointed out that the examples presented above as "not working", may be fixed by provding the <code>common_reference</code>
   for the compared types. As the compared types may be unrelated (one is subobject is the other), such specialization,
   will not have expected semantics of common type - once the <code>Employee</code> will be reduced to only its name,
   it cannot be reconstructed back.</p>

<p>To illustrate, lets as return to our <code>NameLess</code> example, presented at beginning of this section. For the code
   to compile, we need to make sure that the <code>CommonReference&lt;Employee, std::string_view&gt;</code> is satisfied
    - to achieve that we may provide an implicit conversion from <code>Employee</code> to <code>std::string_view</code> 
   that would return <code>name</code> member.</p>

<p>However, this solution is riddled with problems. Not only it is introducing undesired conversion to the <code>std::string_view</code>
   that affects existing code, but fails in situations when we want to provide relation comparing other members of class <code>Employee</code>
   that have <code>std::string type</code>.
   For example, if we will want to write a second relation, <code>SurnameLess</code> that would compare the <code>surname</code> member of the
   <code>Employee</code> class, that also happen to have <code>std::string</code> type, we will also need to introduce conversion to <code>std::string_view</code>
   that would return <code>surname</code> member, which directly conflicts with conversion we have provided to support <code>NameLess</code>.</p>

<p>[ Note: The conversion operator needs to return corresponding members of the <code>Employee</code>, to satisfy semantic requirements
   of the <code>Relation</code> concept, i.e:</p>
<ul>
  <li><code>NameLess{}(e, sv)</code> (<code>e.name &lt; sv</code>), needs to be equivalent to <code>NameLess{}(std::string_view(e), sv)</code> (<code>std::string_view(e) &lt; sv</code>),</li>
  <li><code>SurnameLess{}(e, sv)</code> (<code>e.surname &lt; sv</code>), needs to be equivalent to <code>SurameLess{}(std::string_view(e), sv)</code> (<code>std::string_view(e) &lt; sv</code>).</li>
</ul>
<p>Above requirements cannot be both satisfied at the same time, as they require conversion from <code>Employee</code> to <code>std::string_view</code> to have different semantics. ]</p>

<p>We may attempt to mitigate need of implicit conversion, by providing an specialized common type for the <code>Employee</code> to <code>std::string_view</code>, for example:</p>
<pre>class EmployeeNameView
{
  EmployeeNameView(std::string_view s) : value(s) {}
  EmployeeNameView(Employee const&amp; e) : value(s.name) {}

  std::strong_ordering operator&lt;=&gt;(EmployeeNameView, EmployeeNameView) = default;

private:
  std::string_view value;
};</pre>
<p>And then provide an explicit specialization of <code>common_type</code> (or <code>basic_common_reference</code>) for <code>Employee</code> and <code>std::string_view</code>:</p>
<pre>namespace std
{
  template&lt;&gt;
  struct common_type&lt;Employee, std::string_view&gt;
  { using type = EmployeeNameView; };

  template&lt;&gt;
  struct common_type&lt;std::string_view, Employee&gt;
  { using type = EmployeeNameView; };
}</pre>

<p>Again this solution fails, if we also want to introduce the <code>SurnameLess</code> relation. For these relation we need to specialize <code>common_type</code> for
   <code>Employee</code> and <code>std::string_view</code> to point to <code>EmployeeSurnameView</code> type, that is very similar to the <code>EmployeeNameView</code> with 
   one important difference - the construction of this type from <code>Employee</code> object needs to store view to the <code>surname</code> member.
   This in the end leads to conflicting declaration of <code>common_type</code>, leading to same problem as in case of solution using conversion operator.
   Futhermore above, solutions would not applicable, if the <code>NameLess</code> would accept <code>std::shared_ptr&lt;Employee&gt;</code> (or any other library wrapper
   specialized for <code>Employee</code>), as we cannot specialize <code>common_type</code> or <code>common_reference</code> for types that are not user defined. 
   Which means we cannot use it to allow lookups into <code>vector</code> of optionals or smart pointers.</p>

<p>As we need to provide different <code>common_type</code> specialization for comparison with either <code>name</code> and <code>surname</code>, 
   the other solution is to use a different type to represent such object, so instead of using <code>std::string_view</code> to represent above values,
   we will use specialized object (like above <code>EmployeeNameView</code> and <code>EmployeeSurnameView</code>) when search for value.
   Instead of:</p>
<pre>std::ranges::equal_range(ve, "Kowalski"sv, NameLess{});</pre>
<p>we will write</p>
<pre>std::ranges::equal_range(ve, EmployeeNameView("Kowalski"));</pre>
<p>Note that we not longer need to provide the comparator object, as <code>Employee</code> are comparable with <code>EmployeeNameView</code>, due
   to existence of implicit conversion. Essentially, this solution replaces custom comparison functor (which can be created using lambda)
   with custom type.</p>

<p>Finally, we could drop any attempts to provide an semantically meaningful type for the <code>CommonReference</code> and define <code>common_type</code> to be
   a variant of the <code>std::variant&lt;Employee, std::string_view&gt;</code> (or <code>basic_common_type</code>  to return <code>variant</code> of references).
   Of course this workaround cannot be applied in case of relation accepting standard-library types specialized for user-defined type. 
   Furthermore, it unnecessarily complicates the definition of the comparator operators, as they need to able to compare variant object with correct semantics.</p> 


<h3><a name="motivation.common_reference">3.5. Implementing mathematical comparison</a></h3>

<p>In contrast to previous sections, when we were unable to implement desired ordering (or implement it effectively), in this section
   we will discuss the example ordering, that cannot be implemented as a comparator, due existing specialization of <code>common_type</code>.</p>

<p>Let us consider implementing an <code>MathematicalLess</code> functor, that will compare class of integral types, according
   to mathematical meaning of this relation, i.e. <code>MathematicalLess{}(-1, 1u)</code> return <code>true</code>. We may
   implement it as follows:</p>
<pre>struct MathematicalLess
{
  template&lt;typename T, typename U&gt;
  bool operator()(T t, U u) const
  {
     using UT = std::make_unsigned_t&lt;T&gt;;
     using UU = std::make_unsigned_t&lt;U&gt;;
     if constexpr (std::is_signed_v&lt;T&gt; == std::is_signed_v&lt;U&gt;) // types has same signedness
       return t &lt; u;
     else if constexpr (std::is_signed_v&lt;T&gt;) // U is unsigned
       return t &lt; 0 ? true : UT(t) &lt; u;
     else  // T is unsigned
       return u &lt; 0 ? false : t &lt; UU(u);
  }
};</pre>

<p>Now let us discuss if <code>StrictWeakOrdering&lt;MathematicalLess, unsigned, int&gt;</code>. Firstly, the <code>unsigned</code> and
   <code>int</code> types has a common type: <code>std::common_type_t&lt;unsigned, int&gt;</code> is <code>unsigned</code>. Secondly
   <code>MathematicalLess</code> can be invoked with any combination of objects of type either <code>int</code> or <code>unsigned</code>.
   This means that we are satisfying our syntactic requirements.</code>

<p>However, if we consider following semantic requirement that the invocation of relation <code>r(a, b)</code> is always equivalent to
   invocation <code>r(C(a), C(b))</code>, where <code>C</code> is common reference type for <code>a</code> and <code>b</code>.
   In case of our functor, that requires that <code>MathematicalLess{}(-1, 1u)</code>, is required to return the same value
   as <code>MathematicalLess{}(unsigned(-1), unsigned(1u))</code>, which is equal to <code>false</code>. However, by the design
   of <code>MathematicalLess</code> the result shall be true.</code>.</p>

<p>Note that this problem cannot be fixed without introducing opaque typedefs, as user is not allowed to change the common type
   for built-in types.</p> 

<h2><a name="design">4. Design Decisions</a></h2>

<h3><a name="design.requiring-same-type">4.1. Requiring homogeneous invocation</a></h3>

<p>Even after removal of the <code>CommonReference</code> requirement for the <code>StrictWeakOrdering</code>, this concept will be more strict 
   that the minimal STL1 requirements - the <code>StrictWeakOrdering&lt;F, T, U&gt;</code> requires <code>F</code> requires that <code>F</code>
   is both invocable with combination of types (<code>Predicate&lt;F, T, U&gt;</code> and <code>Predicate&lt;F, U, T&gt;</code>), but also two
   object of the same type (<code>Predicate&lt;F, T, T&gt;</code> and <code>Predicate&lt;F, U, U&gt;</code>).</p>

<p>To illustrate, if we consider and reduced an version of the <code>NameLess</code> comparator:</p>
<pre>struct ReducedNameLess
{
   bool operator()(Employee const&amp; lhs, std::string_view rhs) const
   { return lhs.name &lt; rhs; }

   bool operator()(std::string_view lhs, Employee const&amp; rhs) const
   { return lhs &lt; rhs.name; }
};</pre>
<p>The following invocation compiles and gives correct result:</p>
<pre>std::equal_range(ve.begin(), ve.end(), "Kowalski"sv, ReducedNameLess{});</pre>
<p>as implementation of <code>std::equal_range</code> does not need to invoke supplied comparator on two objects of same collection.
   However, even with the proposed relaxation of the <code>StrictWeakOrdering</code> concept, the range version of the above invocation,
   will still fail to compile:</p>
<pre>std::ranges::equal_range(ve.begin(), ve.end(), "Kowalski"sv, ReducedNameLess{});</pre>

<p>The above additional requirement are required to fulfill the goal of <em>soudness</em> of the design - we explicitly require
   that the requirements of the invoked algorithm could be checkable as the runtime. In case of the <code>equal_range(range, value,
   comp)</code>, we require that the:</p>
<ol>
  <li><code>comp</code> model <em>weak ordering</em> over sum of elements in <code>range</code> and <code>value</code>,</li>
  <li><code>range</code> elements is sorted in order defined by the <code>comp</code>.</li>
</ol>
<p>The second requirement can be checked by simply checking if <code>std::is_sorted(range.begin(), range.end(), comp)</code> is true,
   which impose that <code>comp</code> can be invoked with two elements of supplied range. For the first requirement
   we need to verify axioms described in section <a href="motivation.sound">3.2. Mathematical soundness</a> of this paper - 
   such validation requires <code>comp</code> to be invocable with any combination of types.</code>


<h3><a name="design.totally_ordered_with">4.2. No relaxation for <code>StrictTotallyOrderedWith&lt;T, U&gt;</code></a></h3>

<p>The <code>StrictTotallyOrderedWith&lt;T, U&gt;</code> concept may be viewed as the special case of the
   <code>StrictWeakOrdering&lt;std::less&lt;&gt;, T, U&gt;</code>, where the ordering is represented as <code>operator&lt;</code>
   instead of custom comparator. With such view we may want to apply similar relaxation of requirement for
   this concept.</p>

<p>However, the underlying semantics of the <code>StrictTotallyOrderedWith&lt;T, U&gt;</code> is different 
   than the <code>StrictWeakOrdering&lt;std::less&lt;&gt;, T, U&gt;</code>, as it is meant to represent
   <em>strong order</em> - in contrast to the <em>weak ordering</em> for the <em>strong ordering</em>, 
   if <code>a</code> and <code>b</code> are not ordered (<code>!(a &lt; b) &amp;&amp; !(b &lt; a)</code>),
   then they are the same (<code>a == b</code>).
   In other words, even if situation when types of <code>a</code> and <code>b</code> differs, they
   are different representation of the same entity (e.g. <code>std::string</code> and <code>std::string_view</code>),
   and should have a notion of "common type" (e.g. sequences of characters).</p>

<p>Unfortunately, in some cases, implementing an representation of such common type, may be task that is orders of
   magnitude harder than implementing comparator itself. To illustrate lets as consider the 
   comparison between class representing variable length integer <code>wide_int</code> <code>i</code> and floating
   point value <code>double</code> <code>d</code>. The implementation of such comparison may work as follow:</p>
<ul>
   <li>represent integral part of <code>std::floor(d)</code> as <code>wide_int</code> <code>di</code>,</li>
   <li>if <code>i != di</code>, return <code>i &lt; di</code>,</li>
   <li>otherwise, return <code>false</code>, if fraction part of <code>d</code> (<code>d - std::floor(d)</code>) is non-zero.</li>
</ul> 
<p>In contrast providing a <code>common_type&lt;wide_int, double&gt;</code> would require the user
   to implement class representing arbitrary precision floating point numbers.</code>

<p>Changes proposed in this paper allow to mitigate the problem, by implementing the above compassion
   custom comparison function. Note that without proposed relaxation of <code>StrictWeakOrdering</code>
   requirements, the burden of implementing such common type would be unavoidable.</p> 

<h2><a name="wording">5. Proposed Wording</a></h2>

<p>The proposed wording changes refer to <a href="https://wg21.link/n4762">N4762</a> (C++ Working Draft, 2018-07-07).</p>

<p>Apply following changes to the [concept.relation] Concept <code>Relation</code> section:</p>
<blockquote class="std">
<pre>template&lt;class R, class T, class U&gt;
concept Relation =
  Predicate&lt;R, T, T&gt; &amp;&amp; Predicate&lt;R, U, U&gt; &amp;&amp;
  <del>CommonReference&lt;const remove_reference_t&lt;T&gt;&amp;, const remove_reference_t&lt;U&gt;&amp;&gt; &amp;&amp;</del>
  <del>Predicate&lt;R,</del>
    <del>common_reference_t&lt;const remove_reference_t&lt;T&gt;&amp;, const remove_reference_t&lt;U&gt;&amp;&gt;,</del>
    <del>common_reference_t&lt;const remove_reference_t&lt;T&gt;&amp;, const remove_reference_t&lt;U&gt;&amp;&gt;&gt; &amp;&amp;</del>
  Predicate&lt;R, T, U&gt; &amp;&amp; Predicate&lt;R, U, T&gt;;</pre>

  <dl clas="attribute">
     <dd><del>Let
         <ul>
            <li><code>r</code> be an expression such that <code>decltype((r))</code> is <code>R</code>,</li>
            <li><code>t</code> be an expression such that <code>decltype((t))</code> is <code>T</code>,</li>
            <li><code>u</code> be an expression such that <code>decltype((u))</code> is <code>U</code>, and</li>
            <li><code>C</code> be <code>common_reference_t&lt;const remove_reference_t&lt;T&gt;&amp;, const remove_reference_t&lt;U&gt;&amp;&gt;</code></li>
         </ul></del></dd>
    
     <dd><del>Relation&lt;R, T, U&gt; is satisfied only if
         <ul>
           <li><code>bool(r(t, u)) == bool(r(C(t), C(u)))</code>.</li>
           <li><code>bool(r(u, t)) == bool(r(C(u), C(t)))</code>.</li>
         </ul></del></dd>
  </dl>
</blockquote>

<p>Note that the definition of concept <code>StrictWeakOrder</code> in [concept.strictweakorder] does not need to be updated
   as it does not rely on the existence of <code>common_reference_t&lt;const remove_reference_t&lt;T&gt;&amp;, const remove_reference_t&lt;U&gt;&amp;&gt;</code>
   in any way.</p> 


<h2><a name="acknowledgements">6. Acknowledgements</a></h2>

<p>Casey Carter, Andrzej Krzemieński and Michał Łoś offered many useful suggestions and corrections to the proposal.</p>

<h2><a name="literature">7. References</a></h2>

<ol>
  <li>Alexander Stepanov, Paul McJones,
      "Elements of Programming",
       Addison-Wesley Professional; 1 edition (2009)</li>
  
  <li>Bjarne Stroustrup et al.,
      "A Concept Design for the STL",
      (N3351, <a href="https://wg21.link/n3351">https://wg21.link/n3351</a>)</li>

  <li>Eric Niebler, Casey Carter, Christopher Di Bella,
      "The One Ranges Proposal",
      (P0896R2, <a href="https://wg21.link/p0896r2">https://wg21.link/p0896r2</a>)</li>

  <li>Richard Smith,
      "Working Draft, Standard for Programming Language C++"
      (N4762, <a href="https://wg21.link/n4762">https://wg21.link/n4762</a>)</li>
</ol>


</body></html>
