Type-Erased Wrappers
any_read_stream is a movable, type-erased wrapper for any type modeling ReadStream.
It can be owning or non-owning: you decide upon construction. It models ReadStream itself.
It offers you a possibility to write an algorithm that works with any read stream and that is not a function template:
capy::task<> algo1(capy::ReadStream auto& stream); (1)
capy::task<> algo2(capy::any_read_stream& stream); (2)
| 1 | Taking any read stream via a template argument. |
| 2 | Taking any read stream via a type-erased wrapper. |
The type-erased wrapper comes at a slight run-time cost resulting from indirect calls and an allocation at construction. In return, you get:
-
Not having to ship the implementation of your functions in header files.
-
Much improved compile times.
-
Being able to select the read stream implementation at runtime.
The I/O itself usually costs far more.
The wrapper allocates only when it is created. It allocates storage for the
awaitable (also type-erased), plus storage for the stream when the wrapper owns it.
Each call to read_some reuses the awaitable storage, so steady-state reads never allocate.
You decide whether the wrapper will exclusively own the stream, or if it will only be a reference, by selecting the appropriate constructor
MyReadStream s = makeMyStream();
capy::any_read_stream ws1(&s); (1)
capy::any_read_stream ws2(makeMyStream()); (2)
| 1 | Pointer constructor: you have to make sure the stream outlives the wrapper. |
| 2 | By-value constructor: the wrapper takes the stream by value and manages its lifetime. |
There are analogous wrappers for the WriteStream and Stream concepts:
| Concept | Type-erased wrapper |
|---|---|
The wrappers are not thread-safe.
any_stream allows one read and one write in flight at the same time, but never two of the same kind.
Each class reference states the exact rules.