C++ Logo

std-proposals

Advanced search

Re: [std-proposals] cout << any

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Wed, 4 Jan 2023 13:20:52 -0500
On Wed, Jan 4, 2023 at 10:55 AM Frederick Virchanza Gotham via
Std-Proposals <std-proposals_at_[hidden]> wrote:
>
> It would be nice if we could output an 'std::any' to an 'std::ostream'
> without having to use an 'std::any_cast".

No, it would not.

Runtime type erasure is not like compile-time polymorphism. When you
use a regular template, a function may change its behavior based on
what functionality a type provides. For example `optional<T>` could
(hypothetically) implement an ostream `operator<<` overload if `T` has
such an overload. And if `T` has no such overload, then none will be
provided and attempting to use `operator<<` on such an `optional<T>`
will be a compile error.

Runtime type erasure can't do that. For a type like `any` to work, it
must require specific functionality out of a type up-front. As it
currently stands, `any` requires that the type in question provide
copy functionality. This limits the types that `any` can store, but it
does mean that every `any` can be copied and the copies will work like
actual copies.

Now, you could do a thing where you synthesize a default, such that if
a type doesn't provide `operator<<` behavior, you manufacture some
default functionality. But like, how useful could that possibly be?
Maybe you could output the name of the type, but would that be
meaningful in some way to every user?

Received on 2023-01-04 18:21:02