Composable C++ Function Decorators

Viewed 1618

Python has a very useful feature of function decorators, which, moreover, allows composition. For example, if write a function foo, then you can state that you would like foo to be memoized, but also retried more than a single time in case of a cache miss in which foo also raises an exception, by:

@lru_cache
@retry
def foo(...):

Decorator composability allows developing functions like foo and individual function decorators independently, and then mixing them as needed. It would be nice if we could do so in C++ as well (to the extent possible).

While there are several questions on StackOverflow regarding function decorators, they all seem to generate non-composable ones, due to rigid assumptions on the signature of the decorated function. E.g., consider the excellent top-voted answer to this question. The decoration is of the form

template <typename R, typename... Args>
std::function<R (Args...)> memo(R (*fn)(Args...)) {

Consequently, it cannot be applied to the result of itself (admittedly not much of an issue for the specific decorator use of memoization).

How can we write composable function decorators, then?

2 Answers
Related