Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can explicitly defaulted / deleted functions overload on ref qualifiers?

Tags:

c++

c++11

INTRO

  • Ref qualifiers : A way to dissambiguate the rl-valuness of the implied object. As a quick example, take the following class

    class example
    {
      int member;
    public:
      // ...
      int&       value() &;
      //                 ^
      int&&      value() &&;
      //                 ^^
      int const& value() const&;
      //                      ^
    };
    

    The use of this C++11 feature (syntax marked with ^), allows us to control the version of value() that will be called with

    • l-values
    • temporaries
    • const l-values

    Practically the ref qualification applies to the classe's *this

  • Defaulted / Deleted functions : Specify a special member function as having the compiler generated (default) definition or inaccessible (delete). As an example take

    struct type {
      type(const type&)            = delete;
      type& operator=(const type&) = delete;
    };
    

    The above struct, achieves being non copyable with extremely clear semantics

QUESTIONs

  • Is it possible / valid to combine these features ?
  • Which are the cases where it's explicitly forbidden or bad style ?
  • Is there any use case / pattern for such a combination ? (Eg creating conditional interfaces based rl-valueness quick and easy)
like image 703
Nikos Athanasiou Avatar asked Jun 04 '14 13:06

Nikos Athanasiou


1 Answers

Yes, but there's not much use, as constructors and destructors can't be ref-qualified.

You can ref-qualify assignment operators:

struct S {
  S &operator=(const S &) && = default;
};

int main() {
  S s;
  S() = s;  // OK
  s = S();  // error - LHS must be an rvalue
}

However, I'm somewhat at a loss to imagine what this would be useful for.

like image 62
ecatmur Avatar answered Nov 03 '22 04:11

ecatmur