C++ Logo


Advanced search

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

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Tue, 10 Jan 2023 13:53:12 +0000
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);
        Base *p = as_base<Base>(&obj);
        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

    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.

Received on 2023-01-10 13:53:24