Search⌘ K
AI Features

Solution: Modify the sum Function

Explore how to modify a sum function template using C++20 concepts. Learn to enforce the Arithmetic concept on function parameters to ensure type safety while allowing different argument types for more flexible and generic programming.

We'll cover the following...

Solution

C++
#include <type_traits>
#include <iostream>
#include <string>
template<typename T>
concept Arithmetic = std::is_arithmetic<T>::value;
template <Arithmetic T, Arithmetic T2>
auto sum(T a, T2 b) {
return a + b;
}
int main() {
std::cout << std::endl;
std::cout << "sum(2000, 11): " << sum(2000, 11) << std::endl;
std::cout << "sum(2000, 10.5): " << sum(2000, 10.5 ) << std::endl;
std::string hello("Hello");
std::string world(" World");
// std::cout << "sum(hello, world): " << sum(hello, world) << std::endl;
std::cout << std::endl;
}

The function template sum ...