这种尝试是在C 可靠 /安全的更为Python风格的装饰器中的尝试
Is this attempt at a more python style decorator in c++ reliable / safe
从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
是的,这是一种安全,可靠和传统的方法。
这是有点骇客,因为破坏者被设计为执行清理任务而不是产生关键输出,但这是每个人都使用和满意的黑客。
。做得好!
相关文章:
- Qt VTK交互风格的信号到小部件
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- Pybind11:将元组列表从Python传递到C++
- 如何在c++中使用引用实现类似python的行为
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 递归列出所有目录中的C++与Python与Ruby的性能
- IPC使用多个管道和分支进程来运行Python程序
- 从python中调用C++函数并获取返回值
- 我可以使用条件运算符初始化C风格的字符串文字吗
- Visual Studio 2019:插入多个C++风格的单行注释
- Python 3.7 和 excess_args 的 SWIG 问题
- Python中的for循环与C++有何不同
- 如何在本地机器上运行c++和javascript客户端代码(hackerbank风格)
- 使用Pybind11向Python公开Eigen::张量
- Python str to C++ to Python str
- 使用 rangesv3 在 c++ 中模拟 python 风格的列表理解?
- 这种尝试是在C 可靠 /安全的更为Python风格的装饰器中的尝试
- C 17中的Python风格装饰器
- 以numpy/Python的风格访问OpenCV和C++中的矩阵元素
- c++中Python风格的字符串替换