C++ Logo

std-proposals

Advanced search

Re: [std-proposals] cout << any

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Wed, 4 Jan 2023 20:02:35 -0500
On Wed, Jan 4, 2023 at 5:37 PM Frederick Virchanza Gotham via
Std-Proposals <std-proposals_at_[hidden]> wrote:
>
> On Wed, Jan 4, 2023 at 10:04 PM Andrey Semashev via Std-Proposals
> <std-proposals_at_[hidden]> wrote:
> > Even if you never call the
> > operator<< in your program that uses std::any, the compiler still has to
> > generate the implementation for it - for every type that you ever store
> > in std::any. Eventually this makes std::any too expensive to use for
> > more and more people.
>
>
> If none of the source files in your project have:
>
> #include <any_ostream>
>
> then your program will never have the extra classes and functions I wrote.
>
> And even if you _do_ include my header file and never use anything in
> it, your compiler will eradicate unreachable code.
>
> I don't know why you think std::any has to become any more complicated
> or less efficient.

Because that's not how that works.

Type erasure erases the type. But as part of type erasure, it has to
instantiate a template somewhere that will perform all of the erased
operations for that type erasure. `any` is copyable, and therefore if
you shove an object into it, the type erasure *must* generate a copy
constructor/assignment operator, even if you never copy that
particular `any`. The same goes for `operator<<`: the type erasure
process must generate, at the time you insert the object into `any`,
whatever functionality is needed to use it.

Even if you never call that code, the implementation of `any` must
assume that you will. And therefore, the compiler and type-erasure
machinery must build whatever is needed to do so. Even if it never
gets emitted, it still has to do the work.

And that work cannot be in a separate header file.

Received on 2023-01-05 01:02:45