0

I'm learning about C++20 concepts and constraints and I don't understand why in this case T is considered undefined, yet it seems to work fine in the requires clause. What's wrong here? and why?

If I remove the semicolon, the compiler says U is not a template

error: expected unqualified-id before ‘;’ token
   11 | requires std::integral<T> || std::floating_point<T>;
      |                                                    ^
main.cpp:12:28: error: ‘T’ was not declared in this scope
   12 | constexpr double average(U<T> const &it) {
#include <numeric>
#include <vector>
#include <iostream>
#include <concepts>

template <typename T, std::forward_iterator U>
requires std::integral<T> || std::floating_point<T>;
constexpr double average(U<T> const &it) {
    const double sum = std::accumulate(it.begin(), it.end(), 0.0);
    return sum / it.size();
}

int main() {
    std::vector ints { 1, 2, 3, 4, 5};
    std::cout << average(ints) << '\n';
}
Cedric Martens
  • 1,139
  • 10
  • 23

1 Answers1

0

please read about container concept for the full solution. here is a partial solution just to show a direction.

#include <numeric>
#include <vector>
#include <iostream>
#include <concepts>

template <typename T>
requires requires (std::integral<typename T::value_type>) || (std::floating_point<typename T::value_type>)
constexpr double average(T const &container) {
    const double sum = std::accumulate(container.begin(), container.end(), 0.0);
    return sum / container.size();
}

int main() {
    std::vector ints { 1, 2, 3, 4, 5};
    std::cout << average(ints) << '\n';
}
Alexander
  • 698
  • 6
  • 14