Using Typelist to mimic Decorator Pattern

Using Typelist to mimic Decorator Pattern

With the introduction of Variadic templates in c++, we can now easily define a Typelist, which is a compile-time construct that contains a list of types. In this way, it is similar to an std::tuple, however as opposed to a tuple, a Typelist does not store any data.

A Typelist can simply be defined as 

template <typename... Ts>
struct TypeList
{


};        

Now, since the Typelist can contain any sequence of Types, what if we were to instantiate it with function like types, for e.g. a list of functors.

Lets say we wanted to implement a simplified compile-time mechanism which somewhat mimics a Decorator pattern, in which we have a list of pre-defined operations that we want to perform on a particular object /value.

For this we want to use Typelist and functors such that we could write something like:

using Decorator_Types = Typelist<Decorator1, Decorator2, Decorator3>

MyObj obj{};

applyDecorator<Decorator_Types>(obj); //applies all the Decorator types 

process(obj) //processes the updated object        

To do this we would also need some helper functions for the Typelist. The implementation can be as shown below.

No alt text provided for this image
Tyeplist Definition
No alt text provided for this image
Helper Functions
No alt text provided for this image
Object with very simple sample Decorators
No alt text provided for this image
A templated functor to apply decorators
No alt text provided for this image
Usage
No alt text provided for this image
Output

To view or add a comment, sign in

More articles by Vivek Singh

Explore content categories