Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 442
Hariom Singh Avatar asked Aug 19 '17 02:08

Hariom Singh


People also ask

When should I use templates C++?

Templates are very useful when implementing generic constructs like vectors, stacks, lists, queues which can be used with any arbitrary type. C++ templates provide a way to re-use source code as opposed to inheritance and composition which provide a way to re-use object code.

What is template in C++ with example?

A template is a simple yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types.

Are templates generics?

Key differences between generics and C++ templates: Generics are generic until the types are substituted for them at runtime. Templates are specialized at compile time so they are not still parameterized types at runtime.


1 Answers

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

like image 59
Jarod42 Avatar answered Oct 14 '22 08:10

Jarod42