Nested class or non-nested class?

I have a class A and a list of objects A. A has a function f that must execute every X seconds (for the first instance every 1 second, for an instance of seconds every 5 seconds, etc.). I have a scheduler class that is responsible for executing functions at the right time. What I decided to do was create a new class, ATime, which will contain ptr for instance A and the time A :: f should be done. The scheduler will contain a queue with a minimum priority in Atime.

  • Do you think this is the right implementation?
  • Should ATime be a nested scheduler class?
+3
source share
4 answers

, , , : -)

IMHO ATime , A. , , A. , A ( ) , .

+4

, ...

boost:: function boost:: bind , A. .

, , Boost :

#include <ctime>
#include <queue>
#include <boost/function.hpp>
#include <boost/bind.hpp>

struct Foo
{
    void onScheduler(time_t time) {/*...*/}
};

struct Bar
{
    void onScheduler(time_t time) {/*...*/}
};

typedef boost::function<void (time_t)> SchedulerHandler;

struct SchedulerEvent
{
    bool operator<(const SchedulerEvent& rhs) const {return when < rhs.when;}

    SchedulerHandler handler;
    time_t when;
};

class Scheduler
{
public:
    void schedule(SchedulerHandler handler, time_t when)
    {
        SchedulerEvent event = {handler, when};
        queue_.push(event);
    }

private:
    std::priority_queue<SchedulerEvent> queue_;
    void onNextEvent()
    {
        const SchedulerEvent& next = queue_.top();
        next.handler(next.when);
        queue_.pop();
    }
};

int main()
{
    Scheduler s;
    Foo f1, f2;
    Bar b1, b2;

    time_t now = time(0);
    s.schedule(boost::bind(&Foo::onScheduler, &f1, _1), now + 1);
    s.schedule(boost::bind(&Foo::onScheduler, &f2, _1), now + 2);
    s.schedule(boost::bind(&Bar::onScheduler, &b1, _1), now + 3);
    s.schedule(boost::bind(&Bar::onScheduler, &b2, _1), now + 4);

    // Do scheduling...

    return 0;
}

, Scheduler Foo Bar . Scheduler - " ", , SchedulerHandler.

SchedulerEvent , , boost::function . , - . , Boost.Signal.

, .

+1

, , . ( .)

0

( ), . Scheduler ATime (, detail), . , , - .

, ++ 0x ( , , , , ).

, , Scheduler<A> ( TimedOperation<A>) ( /)?

0
source

Source: https://habr.com/ru/post/1736821/


All Articles