Search code examples
c++cpp-core-guidelines

Use of templates to raise the level of abstraction of code?


I'm going throught T.1 of the CppCoreGuidelines, and there are the following examples

Example 1

template<typename T>
    // requires Incrementable<T>
T sum1(vector<T>& v, T s)
{
    for (auto x : v) s += x;
    return s;
}

Example 2

template<typename T>
    // requires Simple_number<T>
T sum2(vector<T>& v, T s)
{
    for (auto x : v) s = s + x;
    return s;
}

As per the Guideline above the examples are bad conceptually, as it missed an opportunity for a generalization (constrained to low-level concepts of “can be incremented” or “can be added”).

How can I express the above templates in order to be termed as good generalized template?


Solution

  • The bad thing is in the (commented) concept. which are too specific and linked to implementation as they state that Incrementable<T> only restrict to operator += and Simple_number<T> only for + and =.

    They provide a correct concept of "Arithmetic" which provides a more complete set of operation +, +=, =, ...

    So you can substitute one implementation by the other.

    Even better would be to replace vector<T> by a "range_view<T>".

    It is not the implementation which is concerned here, but the concept.

    Some algorithms from STL rely on existence of operator == but doesn't require operator !=, or requires the existence of operator < but not operator >, which make them not generic enough.

    Concept of Orderable<T> is more generic than HaveLess<T>.

    Most algorithm rely on some requirement of the type, but should it have the logical conterpart