这种尝试是在C 可靠 /安全的更为Python风格的装饰器中的尝试

Is this attempt at a more python style decorator in c++ reliable / safe

本文关键字:Python 风格 安全 可靠      更新时间:2023-10-16

从python来到C ,这与我可以像Decorator一样接近Python。

此解决方案感觉有点像一个黑客,因为在函数装饰后要运行的代码在计时器击路仪中被隐式调用。它确实有效。

我的问题是:这是安全可靠的,还是更具体地是在函数返回之后直接调用的计时器类的攻击函数(计时器实例出现在范围之外(。

class Timer{
    time_t time;
    std::string name;
public:
    Timer(std::string name): name(name)
    {
        time = now();
    }
    ~Timer()
    {
        printf("time taken by "%s" was: %dn", name.c_str(), (now() - time));
    }
};

void my_function(){
    Timer _(__func__);
    // function code
}

首先回答您的问题,是的。


我只是写这篇文章,我认为这更像是Python Decorator(就像您可以更改参数(一样。

*测试不佳,只需演示这个想法。

#include <iostream>
#include <chrono>
#include <thread>
using namespace std::chrono_literals;
template<typename T>
auto TimeIt(T callable){
    return [=](auto&&... args){
        auto start = std::chrono::system_clock::now();
        callable(args...);
        auto end = std::chrono::system_clock::now();
        std::chrono::duration<double> diff = end-start;
        std::cout << diff.count() << "sn";
    };
}
void my_function(){
    // function code
    std::this_thread::sleep_for(0.5s);
}
auto my_function_2 = TimeIt(my_function); //you cannot reuse the name, though
int main(){
    my_function_2();
}

wandbox

是的,这是一种安全,可靠和传统的方法。

这是有点骇客,因为破坏者被设计为执行清理任务而不是产生关键输出,但这是每个人都使用和满意的黑客。

做得好!