Why am I getting errors when I define this C++ concept?

Viewed 211

I'm following Josh Lospinoso's C++ Crash Course and I'm at a part where it's trying to show me an example of how to use concepts to constrain a method's parameters, and also wants me to use type_traits. However, I'm getting errors saying that it's argument list is missing and that it has an invalid combination of type specifiers. Here's the concept and the method:

template <typename T>
concept bool Averageable() {
    return std::is_default_constructible<T>::value && requires (T a, T b) {
        { a += b } -> T;
        { a / size_t{ 1 } } -> T;
    };
}

template <Averageable T>
T mean(const T* values, size_t length) {
    T result{};
    for (size_t i{}; i < length; i++) {
        result += values[i];
    }
    return result / length;
}
2 Answers

I think you defined your concept in a wrong way. This is how it should look like:

template <typename T>
concept Averageable =
    std::is_default_constructible<T>::value && requires (T a, T b) {
        { a += b          } -> std::same_as<T>;
        { a / size_t{ 1 } } -> std::same_as<T>;
    };

DEMO

I didn't have C++20 enabled in MVSC. Didn't think that had to be done but it did so everything is good now.

Related