|
CLASSpp Manual
Cosmology reference and developer manual
|
#include <memory>#include <type_traits>#include <utility>Go to the source code of this file.
A non-owning reference to a callable: C++26's std::function_ref, until the code base moves to C++26.
Design, measurements and the alternatives rejected (std::function, templated evolvers): docs/superpowers/specs/2026-10-22-function-ref-callbacks-design.md
A FunctionRef is the (function pointer, void* context) pair that the C interfaces passed by hand, with the compiler writing the forwarding function. A call costs one indirect call, as before, and the callable's body is inlined into the forwarder:
auto derivs = [&](double tau, double* y, double* dy) { perturb_derivs(tau, y, dy, &ppaw); };
evolver_ndf15(derivs, tau_ini, tau_end, y, y_size, options);
It refers to the callable and does not copy it, so the callable must outlive every call through the FunctionRef. It is never null: a callback that may be absent is a std::optional<FunctionRef<...>>, as it would be a std::optional<std::function_ref<...>>.
The interface is the part of std::function_ref the code base uses, spelled the same way, so moving to C++26 is a rename. Every program that compiles against FunctionRef compiles against std::function_ref and does the same. The one difference is deliberate: FunctionRef binds only lvalues. std::function_ref also binds a temporary, which is safe as a function argument but dangles once stored, and options structs store callbacks:
options.output = [&](double x, double* y, double* dy, int i) { ... }; // dangles
Here that line does not compile. Name the lambda first. The guard goes with the rename.