The Fn
, FnMut
and
FnOnce
concepts for working with functors
and callable types.
There are three main concepts that model anything callable:
- A
Fn
represents a callable type which is const and will return the same outputs given the same inputs. - A
FnMut
represents a callable type which is allowed to generate unique outputs on each call. This is the most commonly used of the three. - A
FnOnce
represents a callable type which will only be called once.
As these are concepts, not concrete types, they can not enforce any
behaviour but rather represent a protocol of expectations. Types designed to
satisfy these concepts should adhere to them, and safely handle misuse, such
as panicking (via panic
) if called twice when it is not
supported.
To make a type satisfy Fn
it should have a
const call operator()
, to safisfy FnMut
it
should have a mutable call operator()
and to satisfy
FnOnce
, it should have an
rvalue-qualfied call operator()
.
A Fn
type will also satisfy the other two, since a const
function that chooses not to mutate, or that is called only once, does not
violate the protocol.
Similarly, a FnMut
type will also satisfy
FnOnce
as it is valid to only call it a single time.
The fn
namespace provides matchers for use in the function concepts to
match against and constrain the return type of a function.
NonVoid
will match function types that return a type other than void.Anything
will match function types that return any type.
An example of using NonVoid
to match the return
type of a FnMut
:
// Accepts a function that can be called repeatedly with `i32` and which
// returns something other than void. A void type would break compilation
// as it can not be assigned to a variable, so it rejects functions with a
// void return type.
auto func = [](FnMut<NonVoid(i32)> auto f) {
auto x = f(0);
x += 3;
};
func([](i32) { return 3; });
The same with FnMut
being
type-erased as DynFnMut
to avoid templates. The full type must be specified
when not working with templates, so NonVoid
can
not be used.
auto func = [](DynFnMut<i32(i32)>& f) {
auto x = f(0);
x += 3;
};
func(sus::dyn<DynFnMut<i32(i32)>>([](i32) { return 3; }));
Classes
-
A type-erased object which satisifies the concept
Fn<R(Args...)>
. -
A type-erased object which satisifies the concept
FnMut<R(Args...)>
. -
A type-erased object which satisifies the concept
FnOnce<R(Args...)>
.
Concepts
-
The version of a callable object that may be called multiple times without mutating internal state.
-
The version of a callable object that is allowed to mutate internal state and may be called multiple times.
-
The version of a callable object that may be called only once.