Search⌘ K
AI Features

Solution: Simplifying the Generic Functions

Explore how to simplify generic functions in C++20 by using concepts to enforce type constraints. Understand how the Arithmetic concept improves template safety and clarity, helping you write more robust and maintainable code with templates.

We'll cover the following...

Solution

C++
#include <iostream>
#include <vector>
template<typename T>
concept Arithmetic = std::is_arithmetic<T>::value;
template<Arithmetic T>
T sum(const std::vector<T>& cont, T s) {
for (auto x : cont) s += x;
return s;
}
int main() {
std::cout << std::endl;
std::vector vec{1, 2, 3, 4, 5, 6, 7, 8, 9};
std::cout << "sum(vec, 0): " << sum(vec, 0) << std::endl;
std::cout << "sum(vec, 10): " << sum(vec, 10) << std::endl;
}

The ...