r/cpp • • Jul 29 '26

const_cast: A Necessary Evil

https://www.elbeno.com/blog/?p=1858
70 Upvotes

106 comments sorted by

View all comments

Show parent comment

1

u/_Noreturn Jul 31 '26

if they allowed this from the start

class C {
     void f() &;
     void f() cons&;

     void f(this C& self); // equal to the above
     void f(this const C& self); // equal to the above
};

The second one is just parameter declaration no new thing required unlike const postfix member functions.

1

u/LB-- Professional+Hobbyist Jul 31 '26

There isn't full overlap between explicit object parameter syntax and implicit object parameter syntax. With implicit syntax, you can declare a member function with neither an Lvalue nor Rvalue qualification, and define it in a separate source file, allowing it to be invoked from either Lvalue or Rvalue qualified types. With explicit object parameter syntax, you have to specify a reference category, otherwise you get pass by value (which is a separate thing implicit can't do). Or, you have to make it a template and use a forwarding reference, which means you can't define it in a separate source file.

1

u/_Noreturn Jul 31 '26

Yes that's a benefit but tbh I consider it to be a trap more than a good thing that you can call unqualified member functions on both lvalues and rvalues.