...

/

Understanding the Need for Concepts

Understanding the Need for Concepts

Explore the benefits of concepts in dealing with code readability and error messages.

Introduction to concepts

As briefly mentioned in the introduction to this section, there are some important benefits that concepts provide. Arguably, the most important ones are code readability and better error messages. Before we look at how to use concepts, let’s revisit an example we saw previously and see how it stands in relation to these two programming aspects:

template<typename T>
T add(T const a, T const b)
{
return a + b;
}
Template function add

This simple function template takes two arguments and returns their sum. Actually, it doesn’t return the sum but the result of applying the plus operator to the two arguments. A user-defined type can overload this operator and perform some particular operation. The term “sum” only makes sense when we discuss mathematical types, such as integral types, floating-point types, the std::complex type, matrix types, vector types, etc.

For a string type, for instance, the plus operator can mean concatenation. And for most types, its overloading doesn’t make sense at all. Therefore, just by looking at the declaration of the function, without inspecting its body, we can’t really say what this function may accept as input and what it does. We can call this function as follows:

Press + to interact
add(42, 1); // [1]
add(42.0, 1.0); // [2]
add("42"s, "1"s); // [3]
// add("42", "1"); // [4] error: cannot add two pointers

Note: Uncommenting line 4 in the code above will generate an error.

The first three calls are all good; the first call adds two integers, the second adds two double values, and the third concatenates two std::string objects. However, the fourth call will produce a compiler error because const char* is substituted for the T type template parameter, and the plus operator is not overloaded for pointer types.

Restricting arguments to only arithmetic types

The intention for this add function template is to allow passing only values of arithmetic types, that is, integer and floating-point types. Before C++20, we could do this in several ways. ...