作为引用,这里是最小的例子: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/