Create safer templates with concepts and constraints
Templates are great for writing code that works with different types. For example, this function will work with any numeric type:
template <typename T> T arg42(const T & arg) { return arg + 42; }
But what happens when you try to call it with a non-numeric type?
const char * n = "7"; cout << "result is " << arg42(n) << "\n";
Output:
Result is ion
This compiles and runs without error, but the result is unpredictable. In fact, the call is dangerous and it could easily crash or become a vulnerability. I would much prefer the compiler generate an error message so I can fix the code.
Now, with concepts, I can write it like this:
template <typename T> requires Numeric<T> T arg42(const T & arg) { return arg + 42; }
The requires
keyword is new for C++20. It applies constraints to a template....