C++ Logo

std-proposals

Advanced search

[std-proposals] A drift for c++ decorators;

From: zys <dou1984_at_[hidden]>
Date: Sun, 27 Oct 2024 01:25:11 +0800 (CST)
Dear all:
When I want to execute additional code before functions without changing the source code, there are several approaches I can take:
Use C++ inheritance and override the original function.
Use function hooks at the compile time.
Use lambda functions, etc.
In Python, decorators can assist developers in achieving this and are widely used. Therefore, it is suggested that C++ also adds decorators as a syntactic sugar to help developers quickly implement the execution of extra code before and after functions.
for examples£º
#include<stdio.h>
#include<iostream>


template <classFunc, class... Args>
autoprint_logs(Func&&func, Args&&...args)
{
    printf("this is a log\n");
    returnfunc(std::forward<Args>(args)...);
}


@print_logs // Execute print_logs before executing add.
intadd(inta, intb)
{
    return a + b;
}
intcommon()
{
    add(1, 2); // print "this is a log\n"
    // Replace the add above with the following code at pre-compilation.
    // print_logs(add, 1, 2);
    return0;
}


structmath
{
    @print_logs
    intadd(inta, intb) { return a + b; }
};
intinstead_of_lamda()
{
    math m;
    m.add(1, 2); // print "this is a log\n"
    // Replace the add above with the following code at pre-compilation.
    // print_logs([&](int a, int b)
    // { return m.add(a, b); }, 1, 2);
    return0;
}

Received on 2024-10-26 17:25:16