Default Implementations of Associated Functions

By Douglas Gregor

The concepts specification has contained wording to permit default implementations of associated functions “forever”, which permits one to write concepts that state a set of related operations (e.g., == and !=) while only requiring that the user provide one of those operations. This allows algorithms to be expressed more cleanly without pushing many more requirements on the user. It’s somewhat like using <code>relops</code> in your algorithms or using the <a href=”http://www.boost.org/libs/utility/operators.htm”>Boost.Operators</a> library on your data types, but it applies only within constrained templates. For example, here we write the EqualityComparable concept with both != and ==, related through a default implementation:

auto  concept EqualityComparable<typename T> {
  bool operator==(T, T);
  bool operator!=(T x, T y) { return !(x == y); }
}

This concept will match any type with a suitable operator==, whether or not it has an operator!=. If no operator!= exists, the default implementation of !(x == y) will be used instead. ConceptGCC now supports default implementations, with one caveat: late-checked concept map templates don’t seem to work well with default implementations of associated functions, yet.

6 Responses to “Default Implementations of Associated Functions”

  1. James Says:

    I weep tears of joy that there has been no news on ConceptGCC for so long. If only I could play with yet more C++ wizadry using g++.

  2. Loïc Joly Says:

    What if, in that case, T only defines operator!= ?

  3. Douglas Gregor Says:

    In that case, the auto concept will not match.

  4. Loïc Joly Says:

    Is there a way to specify the auto concept so that it can match in three cases :
    - Both operator== and operator!= are defined
    - operator== only is defined
    - operator!= only is defined

  5. Douglas Gregor Says:

    No, there isn’t.

  6. Tristan Wibberley Says:

    EqualityComparable should provide a default operator != in terms of operator==, rather than the other way round. !operator!=() is usually implementable faster than operator==().

Leave a Reply