C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Allow chaining of -> for normal pointers

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Sun, 8 Jan 2023 21:35:27 +0000
On Sun, Jan 8, 2023 at 7:34 PM Jason McKesson via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> But... that's not what you were asked for. You were asked why this
> feature needs to exist. What the motivation is, beyond merely
> "pointers to pointers are a thing, so there should be a mechanism to
> fully dereference them down to the first non-pointer type". Why is
> this something that needs to be in the standard, when common C++
> idioms and advice are to avoid raw pointers as much as possible?


You mention raw pointers, but 'xdref' works with 'std::unique_ptr' and
also things like 'std::optional' -- it works with anything that can be
dereferenced.

I might add code to 'xdref' to check if the type is an 'std::optional'
and to throw an exception if 'has_value()" returns false.

Sometimes an idea comes to me to develop a solution before I've
discovered the problem. Ideas are coming to me now that I've got
'xdref' written. Like if I have a template function that iterates
through the elements in a container, then for efficiency I can sort a
container of pointers to the elements, but my original template
function can deal with the container of pointers just as though it
were dealing with a container of T's. Similarly a template function
can deal with std::optional<T> instead of just plain T. Or a template
function can deal with std::unique_pointer< std::optional<T> > instead
of just plain T.

Two examples:

template<typename T>
void IncrementEverything(T &container)
{
    for ( auto &e : container )
    {
        ++xdref(e);
    }
}

template<typename T>
void RecordEntry(std::ostream &os, T &&obj)
{
    std::time_t const result = std::time(nullptr);
    os << "Recorded at " << std::ctime(&result) << xdref(obj) << std::endl;
}

Basically you can write a template function and think "I don't care
how many levels of indirection there are, I wanted the root object",
and it there's no object in existence then there'll be an exception
thrown rather than a segfault.

Received on 2023-01-08 21:35:37