Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
concepts
templates
communitycreator

How to go from templates to concepts in C++

Muhammad Ali Shahid

Overview

Templates are a compelling feature of C++. They pass various data types as parameters, so we don’t have to write the same code for different data types.

For example, consider the case in which we need to find the maximum value between two different data types. Rather than writing the same code for two different data types, we can simply write one maximum function and pass the data type as the parameter. This will make it easier for us to maintain the code and increase its reusability.

The following code will do just that:

#include <iostream>
using namespace std;

template <typename U>
// Funtion to find the max value
U maxVal (U firstVal, U secondVal)
{
  return (firstVal > secondVal)? firstVal: secondVal;
}

int main() {
 
 //Calling function with integral data type
 cout << maxVal<int>(2, 3) << endl; 

//Calling same function with double data type
 cout << maxVal<double>(2.3, 3.2) << endl;

  return 0;
}
Templates

For the compiler, it will be something like what is shown below:

Currently, the code written above can accept all data types, even char and string. What if we only wanted to add integral or floating-point types in the function header? This is where concepts come into the picture. With concepts, we can easily express such requirements on the template parameters.

Concepts are an extension of templates. They are used to perform compile-time validation of template arguments through boolean predicates.

In the following example, we will only accept the integrals and floating-point types in the function header with the help of concepts, and return the added value:

#include <iostream>
#include <concepts>

template <typename T>
concept Number = std::integral<T> || std::floating_point<T>;

template <typename T>
requires Number<T>

// Funtion to add two values
auto add(T a, T b) {
  return a+b;
}

int main() {

   //Calling function with integral data type
  std::cout<<add(5,42)<< endl;

  //Calling same function with double data type
  std::cout<<add(3.3,42.6)<< endl;

  return 0;
}
Concepts

One thing to keep in mind here is that it will not work for the following:

std::cout<<add(3,42.6)<<'\n';

Or for this:

std::cout<<add(42.6,3)<<'\n';

For this, we need to carry out a template specialization.

RELATED TAGS

c++
concepts
templates
communitycreator

CONTRIBUTOR

Muhammad Ali Shahid
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring