包装一个功能,该函数采用std :: function< double(doule)>为了传递函数,以获取更多参数
continue
Problem
I have a function double subs(std::function<double(double)> func)
, and I want to wrap it in a new function that looks like this
template<typename... Args> double subsWrap(std::function<double(Args... args)> func)
that applies subs
to some function that takes more inputs as
subs( subs( subs( ... func(...) ) ) )
with each subs
applied to only one of the arguments of func
at a time.
Minimal example
Let's say that we have a function
auto subs = [] (std::function<double(double)> func){return func(2) + func(5.3);};
and we want to apply it to
auto f2=[](double x, double y){return std::sin(x*std::exp(x/y)); };
as
subs( [&f2](double y){ return subs( [&y,&f2](double x){ return f2(x,y); } ); } )
For f2
, this is easy, so there is no need for a wrapper. However, if we want to do the same thing for a function of a greater number of arguments (e.g. double(double,double,double,double,double)
) things start to become complicated.
There has to be a way to do this automatically, but I am not even sure how to start.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将variadic lambdas与
std :: is_invocable
键入特征终止递归呢?在这里,需要对lambda进行明确的返回类型规范,以传播“ Invocability”属性。
[=](auto ... xs){返回func(x,xs ...); }
在任何数量的参数中都可以正式起见,无论func(x,xs ...)
是否可视化。当用nectType
明确指定返回类型时,Sfinae跳入。随着此实现,两种表达式
都会
产生相同的结果。
有趣的是,使用
-O3
优化GCC和Clang可以 并用编译时常数替换subs_wrap(f2)
。使用std :: function
参数编写的类似代码,他们不这样做。这是一种实现这一目标的方法,并稍微修改代码:
What about using variadic lambdas together with
std::is_invocable
type trait to terminate recursion?Here an explicit return type specification for a lambda is needed to propagate "invocability" property.
[=](auto... xs) { return func(x, xs...); }
is formally invocable with any number of arguments, no matter whetherfunc(x, xs...)
is invocable or not. When the return type is specified explicitly withdecltype
, SFINAE jumps in.With this implementation, both expressions
and
will produce the same result.
It's interesting to note that with
-O3
optimization both GCC and Clang can optimize all this code away and replacesubs_wrap(f2)
with a compile-time constant. With similar code written usingstd::function
arguments they don't do it.Here is a way to achieve this with a slight modification of code: