How to best design function that takes an unary predicate

197 views Asked by At

I'm implementing a simple timeout-class which calls a given function when time runs out.

However I'm scratching my head on how to make the function constructor take an unary predicate, e.g. function pointer, std::function, functor or lambda, in the best case avoiding the performance hits if possible. What's important is that I want to allow capturing lambdas. Basically I want the same thing as is possible for the stl-functions std::find_if, std::for_each etc. with the caveat that I need to handle the calls asynchronously. How would I go about this?

Those are the barebones:

#include <iostream>

template <typename... Ts>
class Timeout
{
public:
    using Function = /* ??? */;
    Timeout(uint32_t timeout_ms, Function fn) : timeout_{timeout}, fn_{fn} {
        /* portspecific invocation of task */
        internal_timer(this);
    }
    ~Timeout() {
        /* portspecific destruction of task */
    }

    static void internal_timer(Timeout* callobj) {
        /* portspecific delay */
        callobj->fn_(/* ??? */);
    }
private:
    uint32_t timeout_;
    Function fn_;
};

int main() {}

CODE

Side note: (1) It can be assumed that captured references at the callsite stay intact for the lifetime of the Timeout object. (2) I have left out the portspecific parts, those are not the problem.

0

There are 0 answers