as_fn(3) | CFL Reference Manual | as_fn(3) |
as_fn - prevent evaluation of nested closure
#include <cfl/bind/as_fn.hpp>
template <typename F> auto as_fn (F && f);
auto f = cfn ([] (int u) { return u + 1; });
auto g = cfn ([] (auto && u) { return u (0); });
assert (g (as_fn (f (f (1_c)))) == 2);
as_fn
is short for “as function” and prevents evaluation of a nested closure
otherwise due to be evaluated. As described in bind(3), a closure resulting
from a composition can not directly be used as a function argument to a
higher-order function accepting placeholders (which most CFL functions do),
but must be adapted with as_fn
.
g
above expects a function argument, but f (f (1_c))
returns a value to
g
. To change this as_fn
must be used.
A non-evaluating closure if the argument is an evaluating closure, otherwise a no-op.
as_fn
is not a container function.
Not uncommon, generic programming have break-down cases. Sometimes they become
pillars of the solution, sometimes nuisances. as_fn
is the latter. To its
excuse, CFL is in good company here, both with the standard library and others.
Without any improved readability, it is possible to prevent one layer of closure
evaluation by binding with a 1__
placeholder. However, for two or more layers
as_fn
must still be used instead.
assert ( f (1_c) (0) == 1);
assert ( f (1_c) (1__) (0) == 1);
assert (g (f (1_c) (1__)) == 1);
assert ( f (f (1_c)) (0) == 2);
// XXX ( f (f (1_c)) (1__) (0) == 2);
// XXX (g (f (f (1_c)) (1__)) == 2);
bind(3), cfn(3)