All the answers above are complicated and uses libraries.
My answer here is by far the most simple and doesn't need any library header.
// "DECORATOR.h"
#pragma once
#ifndef DECORATOR_H
#define DECORATOR_H
template<typename T>
class deco
{
T* m_func;
public:
explicit deco(T func);
template<typename ...args>
auto operator()(args... Args);
}
#endif // DECORATOR_H
Now in the Implementation file do the following
// "DECORATOR.cpp"
template<typename T>
inline deco<T>::deco(T func)
:m_func(func)
{
};
// implementing the function call operator
template <typename T>
template <typename ...args>
auto deco<T>::operator()(args ...Args)
{
//Do some stuff defore the decorated function call
// ....
// Call the decorated function.
auto rv = m_func(Args...);
//Do some stuff after the function call
// ....
return rv;
}
End of the story.
Now this is how to use it in your code.
// "main.cpp"
#include "DECORATOR.h"
#include <stdio.h> // just for printf()
// functions to decorate
int add(int a, int b)
{
return a+b;
};
int sub(int a, int b)
{
return a-b;
};
// Main function
int main()
{
// decorate the functions "add", "sub"
deco<decltype(add)> add_Deco(add);
deco<decltype(sub)> sub_Deco(sub);
// call your decorated functions
printf("result of decorated Add =%d\n", add_Deco(5,2));
printf("result of decorated Sub =%d\n", sub_Deco(4,3));
return 0;
}
This is it Folks!
Pros:
The CLASS "deco" has only one data member => small memory foot print
the operator() takes any number of arguments, so you can decorate any function regardless of its number of arguments.
Simple implementation => simple debugging and testing.
Cons: