我已经修改了以下问题的第一个答案,用于制作定期计时器: How do I make the boost/asio library repeat a timer?
我删除了“count”变量,因为我想重复执行的方法不带任何参数进行计算。
编译器因以下错误而失败:
Error C2825 'F': must be a class or namespace when followed by '::' C:\.conan\wkypad\1\include\boost\bind\bind.hpp 75
Error C2510 'F': left of '::' must be a class/struct/union C:\.conan\wkypad\1\include\boost\bind\bind.hpp 75
Error C3646 'type': unknown override specifier C:\.conan\wkypad\1\include\boost\bind\bind.hpp 75
Error C4430 missing type specifier - int assumed. Note: C++ does not support default-int C:\.conan\wkypad\1\include\boost\bind\bind.hpp 75
Error C2039 'type': is not a member of 'boost::_bi::result_traits<R,F>' C:\.conan\wkypad\1\include\boost\bind\bind.hpp 1284
我做错了什么? 我想我对boost :: bind的使用是错误的,但我无法弄清楚确切的原因。
以下是我的代码的相关部分
class ProjectBrowserComponent ...
private:
void fetchData(const boost::system::error_code& /*e*/,
boost::asio::deadline_timer* t);
std::vector<Project> projects;
ProjectsController pc;
std::future<std::vector<Project>> projectsFuture;
int interval_secs = 1;
...
template<typename R>
bool isReady(std::future<R> const& f)
{
Logger::writeToLog("check future");
return f.wait_for(std::chrono::seconds(-1)) == std::future_status::ready;
}
void ProjectBrowserComponent::initData() {
Logger::writeToLog("requesting projects");
projectsFuture = std::async(std::launch::async, &ProjectsController::getProjects, &pc);
Logger::writeToLog("requested projects");
boost::asio::io_service io_service;
boost::asio::deadline_timer timer(io_service, boost::posix_time::seconds(interval_secs));
timer.async_wait(boost::bind(&ProjectBrowserComponent::fetchData, boost::asio::placeholders::error, &timer));
io_service.run();
}
void ProjectBrowserComponent::fetchData(const boost::system::error_code& /*e*/,
boost::asio::deadline_timer* timer) {
if (isReady(projectsFuture)) {
projects = projectsFuture.get();
std::cout << "got projs";
}
else {
timer->expires_at(timer->expires_at() + boost::posix_time::seconds(interval_secs));
// Posts the event
timer->async_wait(boost::bind(&ProjectBrowserComponent::fetchData, boost::asio::placeholders::error, timer));
}
}
答案 0 :(得分:3)
这个怎么样:
timer.async_wait(boost::bind(&ProjectBrowserComponent::fetchData, this, boost::asio::placeholders::error, &timer));
如果绑定成员函数,则必须将它们绑定到类的对象的正确实例。在这里,我将它绑定到this
,我假设你从代码的外观中做了什么。
从评论中注意到:
重要的是要注意,这必须在异步操作的整个持续时间内保持有效。实现此目标的一种流行方法是使ProjectBrowserComponent
继承自enable_shared_from_this
并绑定到shared_from_this()