Re: fail with the following concept code

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Tue, 28 Feb 2023 at 21:22, Watson Romero via Gcc-help
<gcc-help@xxxxxxxxxxx> wrote:
>
> I was trying to learn how concepts work and for some reason the following
> lines of code:
>
> #include <cstddef>
> #include <cstdio>
> #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 }->T;
>         { a / b }->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 char nums_c[]{ 1, 2, 3, 4 };
>   const auto result3 = mean(nums_c, 4);
>   printf("char: %d\n", result3);
> }
>
> produces the following error while running g++ like so:
> g++ listing_6_21.cpp -std=c++20 -o a.out
>
>
> listing_6_21.cpp:9:20: error: return-type-requirement is not a
> type-constraint
>     9 |         { a + b }->T;
>       |                    ^
> listing_6_21.cpp:10:20: error: return-type-requirement is not a
> type-constraint
>    10 |         { a / b }->T;
>       |                    ^
> listing_6_21.cpp:12:1: error: expected declaration before ‘}’ token
>    12 | }
>
> I'm not sure if this is consistent with what should happen but I figured
> I'd inform you guys about it.

This is the expected, correct behaviour for a C++20 compiler.

The Concepts TS used the syntax in your code, but in C++20 you must
use a type-constraint, like so:

{ a + b } -> std::is_same_v<T>;




[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux