[英]Template on member function in lambda deduced using auto
In the code below, events
is an stl container built from template policies where the underlying type is composed from types in inbound and outbound.在下面的代码中,
events
是从模板策略构建的 stl 容器,其中底层类型由入站和出站中的类型组成。
auto events = process::run<inbound, outbound>(args);
After processing events, I need to do some calculations based on runtime parameters.处理完事件后,我需要根据运行时参数做一些计算。 Here's an example:
下面是一个例子:
cool::transform(events.deltas(), [](const auto ¤t) { return current.method(); });
There are several methods we may want to use, ie we may call another method which may or may not return the same underlying type.我们可能想要使用多种方法,即我们可能会调用另一个可能返回或可能不返回相同底层类型的方法。
cool::transform(events.deltas(), [](const auto ¤t) { return current.other(); });
Is there a way to template this so I can declare:有没有办法对此进行模板化,以便我可以声明:
cooler::transform<method>(events.deltas())
Bonus question: Can we use templates to only enable the code if the method actually exists on the underlying type?额外问题:如果方法实际存在于基础类型上,我们是否可以使用模板来仅启用代码?
Is there a way to template this so I can declare:
有没有办法对此进行模板化,以便我可以声明:
Not really - there is no gotcha-free way of passing "a method" as a template parameter.不是真的 - 没有将“方法”作为模板参数传递的无障碍方式。 You will have issues with overloaded/template member functions.
您将遇到重载/模板成员函数的问题。 The lambda solution you currently have is the best one - I suggest shortening
current
to c
and using auto&&
in order to reduce the boilerplate:您目前拥有的 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?
如果方法实际存在于基础类型上,我们是否可以使用模板仅启用代码?
Yes, you can use the detection idiom to check whether or not an expression is valid.是的,您可以使用检测习语来检查表达式是否有效。 I wrote an article that covers it and other more powerful/terser techniques: "checking expression validity in-place with C++17" .
我写了一篇文章,涵盖了它和其他更强大/更简洁的技术: “使用 C++17 就地检查表达式有效性” 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.