CodeBlanks Logo Icon CodeBlanks

Summary - Concepts

Combine concept, requires and standard concepts to write a generic algorithm.

Summary - Concepts

In this group you learned concept, requires, standard concepts, compound requirement and concept overloading.

Concepts name template constraints; the requires expression does compile-time expression checks; std::integral and std::floating_point are ready-made concepts; compound requirements also check the return type and the noexcept condition; concept overloading dispatches type-based overloads at compile time.

Now you will write a generic accumulate algorithm that combines these four. It will be a safe and readable template built with concepts.

Practice Write a generic accumulate

Write the template function template<std::integral T> T accumulate(const std::vector<T>& data). Its body sums the data and returns it. In main create std::vector<int> data{1, 2, 3, 4}; and print the result of accumulate(data) with std::cout.

Starter code

main.cpp
#include <iostream>
#include <vector>
#include <concepts>

// Write the accumulate template function here

int main() {
    // Create data, call it and print
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <vector>
#include <concepts>

template<std::integral T>
T accumulate(const std::vector<T>& data) {
    T sum = T{0};
    for (auto x : data) {
        sum += x;
    }
    return sum;
}

int main() {
    std::vector<int> data{1, 2, 3, 4};
    std::cout << accumulate(data);
    return 0;
}

Expected output

10

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which keyword starts a concept definition?

  • template
  • static_assert
  • concept Correct answer
  • requires

Explanation: The concept keyword starts a concept definition.

2 Match each idea to its description

Term Meaning
concept Named constraint
requires Expression check
std::integral Ready integral concept
compound Return type check

3 the accumulate call

Question
std::cout << ____(data.begin(), data.end());
Answer
std::cout << accumulate(data.begin(), data.end());

Explanation: The accumulate function sums an iterator range.

All lessons in Advanced