gpt4 book ai didi

c++ - 这是在 c++ 可靠/安全中尝试更多 python 风格的装饰器吗?

转载 作者:行者123 更新时间:2023-11-30 03:16:45 28 4
gpt4 key购买 nike

从 python 到 c++,这是我能得到的最接近 python 的装饰器。

这个解决方案感觉有点像 hack,因为在要装饰的函数之后运行的代码在 Timer 析构函数中是隐式调用的。不过它确实有效。

我的问题是:这是否安全可靠,或者更具体地说,是保证在函数返回后直接调用 Timer 类的析构函数(Timer 实例超出范围)。

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


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

最佳答案

首先回答你的问题,是的,它是安全的。


我只是写这个,我觉得这更像 python 装饰器(就像你可以改变参数)。

*没有很好的测试,只是展示这个想法。

#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() << "s\n";
};
}

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

关于c++ - 这是在 c++ 可靠/安全中尝试更多 python 风格的装饰器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56022331/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com