在下面的代码中,events
是一个基于模板策略构建的 STL 容器,其中基础类型由 inbound 和 outbound 类型组成。
auto events = process::run<inbound, outbound>(args);
处理完事件后,我需要根据运行时参数做一些计算。这是一个例子:
cool::transform(events.deltas(), [](const auto ¤t) { return current.method(); });
我们可能想使用几种方法,即我们可以调用另一个方法,该方法可能返回也可能不返回相同的底层类型。
cool::transform(events.deltas(), [](const auto ¤t) { return current.other(); });
有没有办法对此进行模板化以便我可以声明:
cooler::transform<method>(events.deltas())
额外的问题:如果方法实际存在于基础类型上,我们是否可以使用模板仅启用代码?
最佳答案
Is there a way to template this so I can declare:
并非如此 - 没有将“方法”作为模板参数传递的无误方法。您将遇到重载/模板成员函数的问题。您目前拥有的 lambda 解决方案是最好的解决方案 - 我建议将 current
缩短为 c
并使用 auto&&
以减少样板文件:
cool::transform(events.deltas(), [](auto&& c){ return c.method(); });
Can we use templates to only enable the code if the method actually exists on the underlying type?
是的,您可以使用 detection idiom检查表达式是否有效。我写了一篇文章介绍它和其他更强大/更简洁的技术:"checking expression validity in-place with C++17" .
关于c++ - 使用 auto 推导的 lambda 成员函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46915380/