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

2

u/XeroKimo Exception Enthusiast Jul 30 '26 edited Jul 30 '26

Ah I guess that makes sense... You run into a similar problem if you tried to privately inherit a CRTP class and if any of the CRTP's member functions tries to cast to the derived class... So in deducing this' case, f() is a member function of C and if the this auto&& resolves to P, C doesn't have permission to access the C subobject in P...

If there was a way to constrain it so that the deduced type is always going to be C or any of the ref / const combinations this technique was intended to replace then I guess it'd be better.

1

u/_Noreturn Jul 30 '26

If there was a way to constrain it so that the deduced type is always going to be C or any of the ref / const combinations this technique was intended to replace then I guess it'd be better.

There was a proposal by gazper azman to allow

template<typename T : MetaFunc>
void f(T&& t);

syntax, where it did template deduction then apply the meta function which could be like like_t<T,C> and it would work but sadly I think it is desd proposal.

You could workaround it by using a C style cast inside "f" ((like_t<Self&&,C>)*this).dothing() but it is ugly