[英]How do I return a closure from a function?
我希望我的getEnd函數返回一個開始保存的閉包。
當我打電話給這個關閉它應該返回時差...
如何在c ++中實現它?
接下來的事情:
using namespace std;
long microtime() {
timeval time;
gettimeofday(&time, NULL);
long microsec = ((unsigned long long)time.tv_sec * 1000000) + time.tv_usec;
return microsec;
}
std::function<void()> getEnd (){
long start = microtime();
long end() {
return microtime() - start;
}
return end;
};
#include <functional>
std::function<long()> getEnd()
{
long const start = microtime();
return [=]{ return microtime() - start; };
}
請注意,上面將在堆上分配內存,因此對於大多數實際應用程序來說,更好的替代方案是
struct timer {
long const start;
timer(): start(microtime()) {}
long operator()() { return microtime - start(); }
};
timer getEnd() { return timer(); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.