C++ Logo


Advanced search

Re: [std-proposals] Programmer's Control Over Pointer Convertibility

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Tue, 10 Jan 2023 09:50:27 -0500
On Tue, Jan 10, 2023 at 8:53 AM Frederick Virchanza Gotham via
Std-Proposals <std-proposals_at_[hidden]> wrote:
> We can convert any data pointer to 'void*' and back again to its
> original pointer type. We can convert any function pointer to
> 'void(*)(void)' and back again to its original pointer type. There's a
> third kind of pointer convertibility:
> struct Base {};
> struct Derived : Base {};
> Derived obj;
> Base *p = &obj;
> Here the compiler has determined that a 'Derived*' can implicitly
> convert to a 'Base*'. Back in 1983, Stroustrup could have decided that
> we need some sort of cast or operator here, for example:
> Base *p = as_any_base(&obj);
> or:
> Base *p = as_base<Base>(&obj);
> or:
> Base *p = ^&obj; // ^& globbed as one token
> but he decided to allow the implicit conversion.
> Now that we have this implicit conversion in C++23, would it be useful
> at all for us to be able to manipulate it? Say for example something
> like:
> struct Base1 {};
> struct Base2 {
> Base1 m;
> };
> struct Derived : Base2 {
> operator : Base1
> {
> return m;
> }
> };
> The above code snippet would allow us to implicitly cast a 'Derived*'
> to a 'Base1*', or a 'Derived&' to a 'Base1&". In the event of a
> nullptr, the body of "operator : Base1" is not entered -- it simply
> returns a nullptr.

This is basically a form of P0352: achieving the effect of overloading
operator dot by hacking base class conversions to be able to be
re-routed to a member subobject instead of a base class one.

> Now I know some of the regulars here on the mailing list think that
> this is a place where you're supposed to put forward your proposal and
> argue ardently as to what problems your proposal solves and why we
> need to burden the language lawyers and compiler vendors -- but I
> think this can also be a place for thought experiments, and I don't
> think people should hesitate to make weird suggestions because we
> might strike gold one day on something that seemed ridiculous when it
> was first posited.

Can't you do that on Reddit or Stack or elsewhere? Cluttering up this
ML with brainstorming ideas isn't helpful towards this ML's purpose of
making C++ standard proposals better. Having a place for fully-formed,
crafted, and *motivated* proposals that can be reviewed and iterated
on is important.

Received on 2023-01-10 14:50:33