Search
 
SCRIPT & CODE EXAMPLE
 

CPP

how to implement binders and decorators on c++ lik python?

#include <iostream>
#include <functional>

/* Decorator function example,
   returns negative (! operator) of given function
*/
template <typename T>
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 <typename T>
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<decltype(function)>(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);
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: c++ how to skip the last element of vector 
Cpp :: how to shorten code using using c++ in class with typename 
C :: trie tableau c 
C :: c colourful text 
C :: generate n-bit gray code in c 
C :: java.lang.SecurityException: Permission denied (missing INTERNET permission?) 
C :: rename c 
C :: conio.h linux 
C :: find factors of a number in c 
C :: c program hide console window 
C :: random number in c 
C :: string to int c 
C :: c boolean 
C :: font awsome circle info icon 
C :: arduino digital input pins 
C :: best sites for loop practice c 
C :: remove first character from string c 
C :: c convert number to string 
C :: c argv 
C :: pg_restore: error: input file appears to be a text format dump. Please use psql. 
C :: Array Input/Output in C 
C :: accessing elements of 1d array using pointers 
C :: how to read keyboard input in C 
C :: binary tree in c search 
C :: star pattern in c 
C :: malloc contiguous 2d array 
C :: concatenate two strings without standard library in C 
C :: Rounding Floating Point Number To two Decimal Places in C 
C :: #define f_cpu 
C :: argparse allow line break 
ADD CONTENT
Topic
Content
Source link
Name
6+8 =