You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中为何无法使用别名类型实现场景切换?

场景切换逻辑编译失败问题

我实现了一个名为SceneManager的类,其update_scene方法的设计逻辑是:当当前场景的exit标志为true时,切换至该场景通过using next = nextScene声明的下一场景,但这段逻辑无法正常编译,编译器给出的提示信息不够明确。

我的SceneManager代码如下:

template <typename T>
concept SceneType = (std::is_base_of_v<Scene, T> and !std::same_as<T, Scene>);

template <typename T, typename... U>
concept AnyOf = (std::same_as<T, U> || ...);

template <SceneType... Scenes>
struct SceneManager {
    SceneManager() {}
    template <AnyOf<Scenes...> T>
    void change_scene() {
        m_current_scene = T();
    }
    void update_scene() {
        std::visit(
            [this](auto&& val) {
                if (val.exit) {
                    val.on_exit();
                    change_scene<decltype(val)::next>();
                    return;
                }
                val.on_update();
            },
            m_current_scene);
    }
    std::variant<Scenes...> m_current_scene;
};

FirstScene的定义如下:

class FirstScene : public Scene {
   public:
    using next = SecondScene;
    void on_init();
    void on_update();
    void on_exit();
};

注意:硬编码指定下一场景时逻辑可正常运行

void update_scene() {
    std::visit(
        [this](auto&& val) {
            using next = SecondScene;
            if (val.exit) {
                val.on_exit();
                change_scene<next>();
                return;
            }
            val.on_update();
        },
        m_current_scene);
}

我已尝试以下方案但均无效:

  • 公共访问器
  • 使用typedef替代using
  • 硬编码指定下一场景(可运行但失去通用性)

内容的提问来源于stack exchange,提问作者Alvaro Gallo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 21:40:25