#State Machine

1 messages · Page 1 of 1 (latest)

tough nest
#
export module Main;

import std;

export class IState {
public:
    virtual ~IState() noexcept = default;
    virtual void Update() noexcept = 0;
    virtual void Draw() noexcept = 0;
    virtual void Pause() noexcept = 0;
    virtual void Resume() noexcept = 0;
};

export class StateManager final {
private:
    static inline std::stack<std::unique_ptr<IState>> _states{};

public:
    [[nodiscard]]
    static std::unique_ptr<IState>& GetActive() noexcept
    {
        return _states.top();
    }

    static void Push(std::unique_ptr<IState>&& state) noexcept
    {
        if (!_states.empty()) _states.top()->Pause();
        _states.push(std::move(state));
    }

    static void Pop() noexcept
    {
        if (_states.empty()) return;
        _states.pop();

        if (!_states.empty()) _states.top()->Resume();
    }
};

export class Menu final : public IState {
private:
    std::string _title;

public:
    Menu(std::string&& title) noexcept : _title{ std::move(title) } {}
    void Update() noexcept override {}
    void Draw() noexcept override {}
    void Pause() noexcept override {}
    void Resume() noexcept override {}
};

export int main()
{
    StateManager::Push(std::make_unique<Menu>("Test"));
    while (true)
    {
        std::unique_ptr<IState>& active{ StateManager::GetActive() };
        active->Update();
        active->Draw();
    }

    return 0;
}

Just wondering if this is the correct way to handle a state machine.
There's one abstract class called IState and multiple classes will derive this one.

  1. Is polymorphism handled correctly here? or is there anything that I can improve
  2. Do you think I should make some functions constexpr?
south roseBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

tough nest
#

Anyone?? or is it OK

shell comet
#

idk if I'd use this in my actual code, but the model itself looks ok

tough nest
#

!solved