📅  最后修改于: 2022-03-11 14:44:55.529000             🧑  作者: Mango
#include
#include
/* Decorator function example,
returns negative (! operator) of given function
*/
template
auto reverse_func(T func)
{
auto r_func =
[=](auto ...args)
{
return !func(args...);
};
return r_func;
}
/* Decorator function example,
prints result of given function before it's returned
*/
template
auto print_result_func(T func)
{
auto r_func =
[=](auto ...args)
{
auto result = func(args...);
std::cout << "Result: " << result << std::endl;
return result;
};
return r_func;
}
/* Function to be decorated example,
checks whether two given arguments are equal
*/
bool cmp(int x, int y)
{
return x == y;
}
/* Decorator macro */
#define DECORATE(function, decorator) \
decorator(function)
int main()
{
auto reversed = DECORATE(cmp, reverse_func);
auto print_normal = DECORATE(cmp, print_result_func);
auto print_reversed = DECORATE(reversed, print_result_func);
auto print_double_normal = DECORATE(print_normal, print_result_func);
auto print_double_reversed = DECORATE(print_reversed, print_result_func);
std::cout << cmp(1,2) << reversed(1,2) << std::endl;
print_double_normal(1,2);
print_reversed(1,2);
print_double_reversed(1,2);
}