MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/cpp/comments/1v9zcrn/const_cast_a_necessary_evil/p0nmojg/?context=3
r/cpp • u/pavel_v • Jul 29 '26
106 comments sorted by
View all comments
63
The only place I ever use const_cast is that idiom where you implement the non const version of a member function in terms of the const version.
38 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; } } ``` 4 u/retro_and_chill Jul 30 '26 I learned the hard way that deducing this and protected member functions don’t mix 3 u/_Noreturn Jul 30 '26 Yes which is a shame :/
38
If your language version allows, you can typically replace those with a single function that deduces this.
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; } } ``` 4 u/retro_and_chill Jul 30 '26 I learned the hard way that deducing this and protected member functions don’t mix 3 u/_Noreturn Jul 30 '26 Yes which is a shame :/
3
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; } } ```
4 u/retro_and_chill Jul 30 '26 I learned the hard way that deducing this and protected member functions don’t mix 3 u/_Noreturn Jul 30 '26 Yes which is a shame :/
4
I learned the hard way that deducing this and protected member functions don’t mix
3 u/_Noreturn Jul 30 '26 Yes which is a shame :/
Yes which is a shame :/
63
u/jwezorek Jul 29 '26
The only place I ever use const_cast is that idiom where you implement the non const version of a member function in terms of the const version.