C++ Logo


Advanced search

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

From: Breno Guimarães <brenorg_at_[hidden]>
Date: Tue, 10 Jan 2023 11:17:00 -0300
I guess it's useful to, at the very least, add the "what problems your
proposal solves". After all, why would anyone propose an addition to the
language that doesn't solve anything?

You can get clever with conversion operators and overloading of operator to
partially achieve this: https://godbolt.org/z/fdPxbcjrx
Of course, this doesn't solve the actual pointer convertibility, just the
obj to pointer part. But it would be possible to get more and more clever
about it. Like creating a "convertible_ptr" template that would allow
custom conversions.

But why though?

Breno G.

On Tue, Jan 10, 2023 at 10: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.
> 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.
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2023-01-10 14:17:13