C++ 20 Concepts: part 1 (the basics)

  1. a generalized code
  2. better code than hand written code with zero overhead
  3. well specified interfaces on the template method/class usage.

1. The problem with classical template program

#include <iostream>template <typename T>
void print(const T& msg){
std::cout << msg;
}
int main(){
int a{1};
char b{'2'};
std::string msg1{"hello wolrd!"};
print(a);
print(b);
print(msg);

return 0;
}
#include <iostream>
#include <vector>
template<typeneme T>
void print(const T& msg){
std::cout << msg;
}
int main(){
std::vector<int> v{1,2,3,4,5,6};
print(v);
}
// a horrendously long compiler error
source: memegenerator.net

2. The solution: concepts

#include <iostream>
#include <vector>
//first define a concept for print
//lets call it 'Printable'
template<typename T>
concept Printable = requires(std::ostream& os, const T& msg)
{
{os << msg};
};
//now impose the constraint define above on print method
template <Printable T>
void print(const T& msg){
std::cout << msg;
}
note: constraints not satisfied:In substitution of 'template<class T>  requires  Printable<T> void print(const T&) [with T = std::vector<int>]':required for the satisfaction of 'Printable<T>' [with T = std::vector<int, std::allocator<int> >]in requirements with 'std::ostream& os', 'const T& msg' [with T = std::vector<int, std::allocator<int> >]the required expression '(os << msg)' is invalid    {os << msg};
~~~^~~~~~

3. A small exercise

  1. Use the same generic print method without the concept first.
template <typename T>
void print(const T& msg){
std::cout << msg;
}

Conclusion

Support me by becoming a member

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gajendra Gulgulia

Gajendra Gulgulia

I'm a backend software developer and from time to time I also like to explore web development