c++templatesc++20c++-conceptsfunction-templates

How to do a logical 'or' of requirements in a single concept?


I have the following case


template<typename Class>
concept has_member = requires (Class t)
{ 
    // How can I write only if either of the following conditions is satisfied?
    {t.isInterface() }->std::same_as<bool>;
    // or
    {t.canInterface() }->std::same_as<bool>;
    // or
    // ... more conditions!
};

struct A {
    bool isInterface() const { return true; }
};

struct B {
    bool canInterface() const { return true; }
};

void foo(const has_member auto& A_or_B)
{
    // do something
}

int main()
{
    foo(A{}); // should work
    foo(B{}); // should work
}

As I mentioned in the code-comments, I would like to logically or the requirements (in a single concepts), so that class A and B can be passed to the doSomething().

As per my knowledge, the current concept is checking all the requirements, which means a logical and. If I take it apart into different concepts everything works, but I would need more concepts to be written to satisfy the intention.

Is it possible to combine into one? something like pseudocode

template<typename Class>
concept has_member = requires (Class t)
{ 
    {t.isInterface() }->std::same_as<bool>  ||  {t.canInterface() }->std::same_as<bool>;
    // ... 
};

Solution

  • Is it possoble to combine into one?

    Yes, it is possible. You can write the conjunction of two requires as follows:

    template<typename Class>
    concept has_member = 
        requires (Class t) { {t.isInterface() }->std::same_as<bool>; }
        || //---> like this
        requires (Class t) { {t.canInterface() }->std::same_as<bool>;};
    // ... more conditions!
    

    Demo