From d18f5bdb682a1d9c6e3a191926bfd46d36e813c1 Mon Sep 17 00:00:00 2001 From: Ben Longbons Date: Wed, 17 Apr 2013 13:22:58 -0700 Subject: Force timers to be managed --- src/common/timer.t.hpp | 42 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) (limited to 'src/common/timer.t.hpp') diff --git a/src/common/timer.t.hpp b/src/common/timer.t.hpp index 67d7450..ee9b5d2 100644 --- a/src/common/timer.t.hpp +++ b/src/common/timer.t.hpp @@ -2,6 +2,9 @@ #define TIMER_T_HPP # include +# include + +struct TimerData; /// An implementation of the C++ "clock" concept, exposing /// durations in milliseconds. @@ -21,8 +24,43 @@ public: typedef milli_clock::time_point tick_t; /// The difference between two points in time. typedef milli_clock::duration interval_t; +/// (to get additional arguments, use std::bind or a lambda). +typedef std::function timer_func; -/// Opaque type representing an active timer. -struct TimerData; +class Timer +{ + friend struct TimerData; + TimerData *td; + + Timer(const Timer&) = delete; + Timer& operator = (const Timer&) = delete; +public: + /// Don't own anything yet. + Timer() : td(nullptr) {} + /// Schedule a timer for the given tick. + /// If you do not wish to keep track of it, call disconnect(). + /// Otherwise, you may cancel() or replace (operator =) it later. + /// + /// If the interval argument is given, the timer will reschedule + /// itself again forever. Otherwise, it will disconnect() itself + /// just BEFORE it is called. + Timer(tick_t tick, timer_func func, interval_t interval=interval_t::zero()); + + Timer(Timer&& t); + Timer& operator = (Timer&& t); + ~Timer() { cancel(); } + + /// Cancel the delivery of this timer's function, and make it falsy. + /// Implementation note: this doesn't actually remove it, just sets + /// the functor to do_nothing, and waits for the tick before removing. + void cancel(); + /// Make it falsy without cancelling the timer, + void detach(); + + /// Check if there is a timer connected. + explicit operator bool() { return td; } + /// Check if there is no connected timer. + bool operator !() { return !td; } +}; #endif // TIMER_T_HPP -- cgit v1.2.3-70-g09d2