Tutorial by Examples

Type erasure is a way to hide the type of an object from code using it, even though it is not derived from a common base class. In doing so, it provides a bridge between the worlds of static polymorphism (templates; at the place of use, the exact type must be known at compile time, but it need not b...
C++ thrives on what is known as a Regular type (or at least Pseudo-Regular). A Regular type is a type that can be constructed and assigned-to and assigned-from via copy or move, can be destroyed, and can be compared equal-to. It can also be constructed from no arguments. Finally, it also has supp...
std::function type erases down to a few operations. One of the things it requires is that the stored value be copyable. This causes problems in a few contexts, like lambdas storing unique ptrs. If you are using the std::function in a context where copying doesn't matter, like a thread pool where ...
Not all type erasure involves virtual inheritance, allocations, placement new, or even function pointers. What makes type erasure type erasure is that it describes a (set of) behavior(s), and takes any type that supports that behavior and wraps it up. All information that isn't in that set of beha...
This example uses C++14 and boost::any. In C++17 you can swap in std::any instead. The syntax we end up with is: const auto print = make_any_method<void(std::ostream&)>([](auto&& p, std::ostream& t){ t << p << "\n"; }); super_any<decltype(print...

Page 1 of 1