我有一个类来存储一个函数,当它被调用时,它会存储函数的运行时间。它对 void 返回类型函数很好。但是当我想获取存储函数的返回类型时,我得到了一个“不应该忽略的空值”。我不能专门化模板,因为返回类型不是协变的(据我所知)。
所以下面的课程很糟糕。
class TimeDurationOperation {
public:
TimeDurationOperation(boost::function<void(void)> operation_)
: operation(operation_) { }
template <typename R> R operate() {
const boost::posix_time::ptime start =
boost::posix_time::microsec_clock::local_time();
R return_value = operation();
const boost::posix_time::ptime stop =
boost::posix_time::microsec_clock::local_time();
elapsed = stop - start;
return return_value;
}
boost::posix_time::time_duration elapsed_time() const {
return elapsed;
}
private:
boost::function<void(void)> operation;
boost::posix_time::time_duration elapsed;
};
工作版本操作()函数:
void operate() {
const boost::posix_time::ptime start =
boost::posix_time::microsec_clock::local_time();
operation();
const boost::posix_time::ptime stop =
boost::posix_time::microsec_clock::local_time();
elapsed = stop - start;
}
我想这样称呼它:
TimeDurationOperation tdo(boost::bind(detail::fun1, 2000));
tdo.operate();
std::cout << tdo.elapsed_time() << std::endl;
和
TimeDurationOperation tdo2(boost::bind(detail::fun2, 500));
int r = tdo2.operate<int>();
std::cout << tdo2.elapsed_time() << " and returned: " << r << std::endl;
你有什么建议?