Overview
Explore how C++ functions evolved from being too specific or too generic. Understand issues like narrowing conversions and template errors, and discover how C++20 concepts provide safer, clearer ways to define template requirements for improved generic programming.
We'll cover the following...
We'll cover the following...
Until C++20, we have two diametral ways to think about functions or user-defined types (classes). Functions or classes can be defined on specific types or on generic types. In the second case, we call them to function or class templates.
There exist two extremes while talking about functions in C++. Let’s take a closer look at two function implementations:
Too Specific Versus Too Generic
Too Specific
#include <iostream>
void needInt(int i){ // 1
std::cout<< i << std::endl;
}
int main(){
double d{1.234};
needInt(d);
}
...Too Generic
#include <iostream>
template<typenameT>
T gcd(T a, T b){
if( b == 0 ){
return a;
}else{
return gcd(b, a % b);
}
}
int main(){
...