JLospinoso / ccc

Companion Code for C++ Crash Course

Home Page:https://ccc.codes

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Listing 6-21 Concepts - Working example

nmadani opened this issue · comments

I could not compile the example with G++ version 10. The following modification worked. Is it correct? (Sorry about the format - can't seem to get posting code snippets correctly).

#include <iostream>
#include <type_traits>
#include <typeinfo>

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

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

int main() {
int nums_i[]{1, 2, 3, 4, 5};
auto mean_i = mean(nums_i, sizeof(nums_i) / sizeof(nums_i[0]));
std::cout << mean_i << std::endl;

double nums_d[]{1.0, 2.0, 3.0, 4.0};
auto mean_d = mean(nums_d, sizeof(nums_d) / sizeof(nums_d[0]));
std::cout << mean_d << std::endl;

char char_array[]{'a', 'b', 'c', 'd'};
auto mean_c = mean(char_array, sizeof(char_array) / sizeof(char_array[0]));
std::cout << mean_c << std::endl;

// char* string_array[]{"a", "b", "c", "d"};
// auto mean_s = mean(string_array, sizeof(string_array) / sizeof(string_array[0]));
// std::cout << mean_c << std::endl;

return 0;

}

Hi, thanks for the issue! The book printed before Concepts finalized in C++20, so it uses the "Concepts TS" which is different. The next version of the book will use the C++20 standard.