template<class Lower>
auto is_gt(Lower&&l){
return [=](auto&&x){ return l<x; };
}
template<class Higher>
auto is_lt(Higher&&l){
return [=](auto&&x){ return x<l; };
}
template<class L, class R>
auto also(L&& l, R&& r){
return [=](auto&&x){return l(x)&&r(x); };
}
template<class L, class R>
auto either(L&& l, R&& r){
return [=](auto&&x){return l(x)||r(x); };
}
template<class Lower, class Upper>
auto between(Lower&& l, Upper&& u){
return also(is_gt(l), is_lt(u));
}
是一些玩具。
然后:
if (either(between(90,97), is_gt(122))(ncode[i]+key[ikey])) {
这可以做得更流畅一些。如果我们将谓词定义为返回bool 的函数对象,它支持&& 和|| 和~ 重载,并让我们上面的玩具返回谓词,我们得到:
if (( between(90,97) || is_gt(122))(ncode[i]+key[ikey])) {
摆脱 either 前缀噪音。
要在非int 情况下提高效率,请通过移动捕获边界。
template<class F>
struct predicate_t:F{
predicate_t(F const& f):F(f){}
template<class F2>
friend auto operator&&(predicate const& f1,predicate<F2> const& f2){
auto r=[=](auto&&...args){
return f1(args...)&&f2(args...);
};
return predicate_t<decltype(r)>(r);
}
template<class F2>
friend auto operator||(predicate const& f1,predicate<F2> const& f2){
auto r=[=](auto&&...args){
return f1(args...)||f2(args...);
};
return predicate_t<decltype(r)>(r);
}
template<class F2>
friend auto operator!(predicate const& f1){
auto r=[=](auto&&...args){
return !f1(args...);
};
return predicate_t<decltype(r)>(r);
}
};
template<class F>
predicate_t<std::decay_t<F>>
predicate(F&&f){
return std::forward<F>(f);
}
上述每个toy 函数都返回return predicate(lambda); 而不是lambda。
此代码在使用时更简单、更简洁,运行时间开销为零,但与传统 C++ 的编码风格不同。