lundi 16 août 2021

Minimum syntax to guarantee no dynamic memory with std::function

Quite often I want to write higher order functional code like

void f(int value, const std::function<void(int)>& callback);

int x, y=5;
f(y, [&](int result) { x = result; });

In cases like these, I would like to be able to guarantee that the std::function constructor does not allocate any memory. The guarantees in the spec are... hard to read. There seems to be some guarantees surrounding reference_wrapper, but I have not been able to get them to work cleanly, due to what I think are lvalue vs rvalue issues. I end up with

auto callback = [&](int result) { x = result; };
f(y, std::ref(callback));

In many of these cases, I want to leverage virtual functions, so I can't just template these issues away (although I have played with using a wrapper that accepts the lambda type as an argument, and wraps it with std::ref, sidestepping any issues regarding temporaries)

What is the minimum amount of syntactic boilerplate needed to ensure this pattern does not allocate any memory?

Aucun commentaire:

Enregistrer un commentaire