C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Enhance concepts to check for member field type

From: Ville Voutilainen <ville.voutilainen_at_[hidden]>
Date: Wed, 20 Mar 2024 11:38:04 +0200
On Wed, 20 Mar 2024 at 11:33, Gergely Nagy via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> Hey,
>
> Imagine you have two structs:
>
> struct A { int x; };
> struct B { int& x };
>
>
> and you want to write a concept that can differentiate between them.
>
> template<typename T>
> concept IsAKind = requires(T t)
> {
> { t.x } -> std::same_as<int>;
> };

Use a nested-requirement:

#include <concepts>

struct A { int x; };
struct B { int& x; };

template<typename T>
    concept IsAKind = requires(T t)
    {
        requires std::same_as<int, decltype(t.x)>;
    };

int main()
{
    static_assert(IsAKind<A>);
    static_assert(!IsAKind<B>);
}

Received on 2024-03-20 09:38:18