Concept with 2 type

46 Views Asked by At

I have a concept that check if the operator< is available to be used on 2 types:

template<class T, class _T>
concept LsOp = requires (T r, _T l)
{
    { r < l } -> bool;
};

And I wan't to use it as something like:

template<class T>
class MyClass
{
public:
    template<LsOp _T>
    [[nodiscard]] bool operator<(const _T &_val) const
    {
        return m_value < _val;
    }

private:
    T m_value;
};

But I don't know what should I change in the syntax to make it work.

1

There are 1 best solutions below

0
Sam Varshavchik On BEST ANSWER

For starters, symbols that begin with an underscore and an uppercase letter are reserved for the C++ library, and should not be used.

Secondly, the following compiles with gcc 13:

#include <concepts>

template<class _t, class _u>
concept LsOp = requires (_t r, _u l)
{
    { r < l } -> std::same_as<bool>;
};

template<class _t>
class MyClass
{
public:

    template<LsOp<_t> u>
    [[nodiscard]] bool operator<(const u &_val) const;
};

void foo()
{
    MyClass<int> bar;

    bool yes = bar < 4.0;             // OK

    bool no = bar < "foobar";         // ERROR
}