Search code examples
c++constraintsc++-conceptsmember-functionsref-qualifier

How to replace ref-qualifiers of member functions with concept?


Is it possible to replace following ref-qualifiers with concepts?

That is, instead of

struct S 
{
   void func() && {}
   void func() & {}
};

have something like this

struct S 
{
   void func() requires rvalue_concept< decltype(*this) > {}
   void func() requires lvalue_concept< decltype(*this) > {}
};

Note: This is not a duplicate of How can I make a forwarding-reference parameter bind only to rvalue references? because my question is about checking whether the struct S is used as an r-value-reference, but the other question is about a function which shall only accept r-value-references.


Solution

  • Is it possible to replace ref-qualifiers with concepts?

    You can use the explicit object parameter syntax introduced in , which allows us to deduce the type of this. With that, you could write:

    template<typename T>
    concept rvalue_concept = std::is_rvalue_reference_v<T&&>;
    
    template<typename T>
    concept lvalue_concept = !rvalue_concept<T>;
    
    struct S 
    {
        template<typename Self>
        void func(this Self&& self) requires rvalue_concept<Self> 
        {
            std::cout << "rvalue version called\n";
        }
    
        template<typename Self>
        void func(this Self&& self) requires lvalue_concept<Self> 
        {
            std::cout << "lvalue version called\n";
        }
    };
    

    See live demo