C++模板类型循环和指向模板实例的非模板指针

标签 c++ templates events variadic-templates circular-dependency

作为引用,这里是最小的例子:http://coliru.stacked-crooked.com/a/75354688a0a6af64
在这个例子中,我有一个模板类型循环的问题,在我看来,可以通过两种方式解决:

  • 制作 Controller模板类和 Event成员指针 指向模板类实例的非模板指针( 但是如何?)
  • 使用 std::any或类似的东西来保留 Controller类非模板(如示例中所示,但不编译)

  • 使这项工作干净利落的最佳方法是什么?
    编辑:链接更新

    最佳答案

    您不能完全键入接受模板参数的删除仿函数。
    但是,如果您知道要处理的模板参数的子集,std::any/std::variant可能有帮助:
    在您的情况下,不受支持的事件不执行任何操作,因此“您的” Controller :

    template <typename ... Modules>
    class Controller {
    public:
        std::tuple<Modules...> modules;
            
        template<typename evt_t>
        void emit(evt_t event) { 
            std::apply([this](auto&&... args) {((args.dispatch(Event<evt_t>{event, this})), ...);}, modules);
        }
            
        Controller(std::tuple<Modules...> _modules) : modules{_modules}{}
    };
    
    变成
    class Controller {
        std::function<void(std::any)> func;
    public:
        template<typename evt_t>
        void emit(evt_t event) {
            func(event);
        }
    
        template <typename ... Modules, typename EventTags>
        Controller(std::tuple<Modules...> tmodules, EventTags event_tags)
        {
            func = [=, this](std::any any_ev){
                auto f = [&, this](auto tag){
                    using EventType = typename decltype(tag)::type;
                    if (auto* ev = std::any_cast<EventType>(&any_ev)) {
                        std::apply([=, this](auto&&... modules) {((modules.dispatch(Event<EventType>{*ev, this})), ...);}, tmodules);
                    }
                };
                std::apply([&f](auto... tags){ (f(tags), ...); }, event_tags);
            };
        }
    };
    
    Demo

    关于C++模板类型循环和指向模板实例的非模板指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62652638/

    相关文章:

    c++ - 如何替换给定类型中的模板参数?

    c# "OR"事件委托(delegate)返回 bool

    javascript - Angular 2 不检测@HostBinding 的变化

    java - 我需要在单击 JToggleButton 时显示 JPanel

    c++ - 链接来自另一个文件的函数时,Qt 上的错误 LNK 2019

    c++ - 在 C++ 中将十六进制字符串转换为字节

    c++ - 适用于 Windows 平台的 C/C++ 调用图实用程序

    c++ - boost::condition 不存在 - condition 不是 boost 的成员

    c++ - 在函数模板的显式特化声明中推导尾随模板参数(无函数参数推导)

    c++ - 在不指定具体类型的情况下传递模板模板参数