Use Cases for Numbers
Let’s see a couple of real-world examples and areas where concepts are applicable.
We'll cover the following...
Recap
So far in this course, we’ve seen what concepts are and why they were introduced in C++20. We’ve also discussed how concepts can be used with functions, classes, and templates. We’ve explored what concepts are shipped with the standard library as well as how to write our own. In the previous chapter, we saw how to use constraints with various types of concepts.
Using Numbers
We’ve been playing with a concept called Number
throughout the entire course. Let’s go over a quick reminder why:
Press + to interact
#include <concepts>#include <iostream>template <typename T>concept Number = std::integral<T> || std::floating_point<T>;auto add(Number auto a, Number auto b) {return a+b;}int main() {std::cout << "add(1, 2): " << add(1, 2) << '\n';std::cout << "add(1, 2.5): " << add(1, 2.14) << '\n';// std::cout << "add(\"one\", \"two\"): " << add("one", "two") << '\n';// error: invalid operands of types 'const char*' and 'const char*' to binary 'operator+'std::cout << "add(true, false): " << add(true, false) << '\n';}
Before C++20
Our problem is that even though we only want to accept integrals and floating-point numbers, boolean values are also accepted. They are accepted because bool
is an ...