Reputation:
I got this code from a a github repository. I copied the code exactly as it is however I am still getting an error that says the declaration has no storage class or type specifier where it says concept on the first template declaration. Here is the code, the error is where the comment is:
#include <cstddef>
#include <type_trait>
#include <cstdio>
template<typename T>
concept bool Averageable() { // Here is where the error appears, at concept
return std::is_default_constructible<T>::value && std::is_copy_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;
}
int main() {
const double nums_d[] { 1.0f, 2.0f, 3.0f, 4.0f };
const auto result1 = mean(nums_d, 4);
printf("double: %f\n", result1);
const float nums_f[] { 1.0, 2.0, 3.0, 4.0 };
const auto result2 = mean(nums_f, 4);
printf("float: %f\n", result2);
const size_t nums_c[] { 1, 2, 3, 4 };
const auto result3 = mean(nums_c, 4);
printf("float: %d\n", result3);
}
The expected output is:
double: 2.500000
float: 2.500000
size_t: 2
Upvotes: 1
Views: 186
Reputation: 96326
C++20 uses a different syntax for concepts. Your code probably targets some old concepts proposal.
Also there are few typos here: T result();
, #include <type_trait>
, ...
Here's a fixed version:
#include <cstddef>
#include <cstdio>
#include <concepts>
#include <type_traits>
template<typename T>
concept Averageable =
std::is_default_constructible<T>::value && std::is_copy_constructible<T>::value && requires(T a, T b) {
{ a += b } -> std::convertible_to<T>;
{ a / size_t{ 1 } } -> std::convertible_to<T>;
};
template<Averageable T>
T mean(const T* values, size_t length) {
T result = 0;
for (size_t i{}; i < length; i++) {
result += values[i];
}
return result / length;
}
int main() {
const double nums_d[] { 1.0f, 2.0f, 3.0f, 4.0f };
const auto result1 = mean(nums_d, 4);
printf("double: %f\n", result1);
const float nums_f[] { 1.0, 2.0, 3.0, 4.0 };
const auto result2 = mean(nums_f, 4);
printf("float: %f\n", result2);
const size_t nums_c[] { 1, 2, 3, 4 };
const auto result3 = mean(nums_c, 4);
printf("float: %zu\n", result3);
}
It works on GCC 10 here.
Upvotes: 3