Home > OS >  C 20 Concepts/Requires clauses
C 20 Concepts/Requires clauses

Time:11-15

I would be really grateful if somebody could explain how C 20 compilers (MSVC 2022 in my case) are able to compile the following, why does the Simple concept have no effect?

template <typename T>
concept Simple = requires(T t)
{
    std::is_trivial_v<T> == true;
};


void foo(Simple auto s) {
    std::cout << "bar";
}


int main(int argc, char** argv)
{
    using Bytes = std::span<std::byte>;

    Bytes b;

    static_assert(false == std::is_trivial_v<Bytes>);

    foo(b);  //compiles and prints "bar"
}

CodePudding user response:

template <typename T>
concept Simple = requires(T t)
{
    std::is_trivial_v<T> == true;
};

This checks if expression std::is_trivial_v<T> == true is well-formed, ignoring its value.

To check if the expression is truthy, add a nested requires:

template <typename T>
concept Simple = requires(T t)
{
    requires std::is_trivial_v<T>/* == true*/;
};

Or just put it outside of requires:

template <typename T>
concept Simple = std::is_trivial_v<T>;
  • Related