dimanche 3 octobre 2021

Generic decorator inspired by functional programming

I made a generic decorator in C++20 with concept for specialization. The idea is to be able to define only one function in the decorator to decorate all functions in a class.

You may try it. It's better to read it at the same time than reading this post.

This decorator is inspired by functional programming:

There is two king of functions : getter that return a value and don't modify the object and setter that returns a modified copy of the object.

This decorator heavily uses template. To call the A getter function, I need to call the function of the class decorating the root class:

classe->f<F::Get, F::A>()

The f function name must be used to be specialized by decorator.

The first argument in template is to tell if I want to get a value (and just return the value) or if I want to set a value (and return a modified clone of the object).

The second argument is the name of the function. The bad thing is that I need an enum with all possible name of functions, which is bad.

I split the get and the name of the function on purpose. So, I can access multiple level of component (classe->f<F::Get, F::A, F::B>()). I know this could be considered bad in programming but I want to avoid boilerplate code.

Questions are:

  • how can I get ride of the huge enum that have all possible name of functions ?
  • do you have an idea to improve the style ? classe->f<F::Get, F::A>() must be used everywhere and it's really different of a classic classe->a(). On the other side, the f function is the only way to tell "please, decorate me".
  • if I want to decorate a class that don't respect the f style, I need to write a glue. How can I avoid it ?

I tried to be conceived but I can expand/improve my explanation.

Aucun commentaire:

Enregistrer un commentaire