The Challenge with Polymorphic Temporaries

In modern C++, passing a heterogenous collection of polymorphic objects to a function often introduces unwanted boilerplate. The traditional approach uses std::vector<std::unique_ptr<Base>>. While safe, this pattern requires heap allocations and verbose initialization like std::make_unique<Derived>(), which feels unnecessary when the objects only need to live for the duration of a single function call.

When object lifetimes are strictly bounded by a function call, developers often look to non-owning references like std::reference_wrapper<const Base>. However, attempting to initialize a std::vector<std::reference_wrapper<const Base>> with temporaries directly fails to compile.

Why std::reference_wrapper Rejects Temporaries

std::reference_wrapper is explicitly designed to prevent dangling references. To enforce this, its constructor taking an rvalue reference (a temporary) is deleted: