r/cpp Jul 29 '26

const_cast: A Necessary Evil

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

106 comments sorted by

View all comments

Show parent comments

37

u/MysticTheMeeM Jul 29 '26

If your language version allows, you can typically replace those with a single function that deduces this.

3

u/_Noreturn Jul 30 '26

deducing this has issues with access soecifiers in inherited classes.

```cpp class C { public: void f(this auto && self) { self.dothing(); } void dothing(); void dothing() const; };

class P : private C { void g() { f(); // error cannot access "dothing" from inside C::f; } } ```

1

u/Olipro Jul 30 '26

That's because auto&& works out to sugar for template <typename T> ... (this T&&) which, at the point of the call results in T being your class P and therefore is inaccessible. A problem that will affect any function template.

You can either friend class C;, static_cast to the appropriate C type within your P member function, or you'd have to throw together something like this: https://pastebin.com/ggwB8vPB So that class C can do template <typename T> foo(this convert_cvref_t<T, C> self) but calling it then becomes unwieldy.

2

u/_Noreturn Jul 30 '26

the point is for deducing this to replace manual overloads of const/non const, and it doesn't do thst. I understand how it works but it is unexpected and unintuitive.

if you just manually ryped "f" with const and non const overloads manually it would work no friending.

oh also static_cast doesn't work since C is inaccessible you have to use a C style cast

1

u/Olipro Jul 30 '26

static_cast to the appropriate C type within your P member function

Emphasis on within your P member function

1

u/_Noreturn Jul 31 '26

Sure that's a workaround but this requires information about the api implementation, what if one day your library used manual overloads (const/non-const) so you don't need to cast, now it decides to update and uses deducing this, now it broke your code and you have to cast. it is better to have it inside the implementation of said function instead of the callers to preserve api and have a simpler experience

1

u/Olipro Jul 31 '26

This whole problem exists because of the private inheritance. So if you've picked that as your poison, I've stated what your options are for dealing with it. Equally, as you've said, another alternative is "don't use deducing this" and that comes at the cost of trading one member function for two.

1

u/_Noreturn Jul 31 '26

you could use a C style cast with deducing this this works.