Search code examples
c++c++11lambdafunctorstd-function

Can a class written to work with a function object also work with a lambda or std::function type?


I've written a template class to work with a no-argument void-returning function object:

//...Class declaration here...

template<class FunctionObject>
Alarm<FunctionObject>::Alarm(const FunctionObject& fn)
    : StopWatch(), _delegate(fn), _tickTime(1.0), _run_count(-1) { /* DO NOTHING */ }

template<class FunctionObject>
Alarm<FunctionObject>::Alarm(double tickTime, const FunctionObject& fn)
    : StopWatch(), _delegate(fn), _tickTime(tickTime), _run_count(-1) { /* DO NOTHING */ }

template<class FunctionObject>
Alarm<FunctionObject>::Alarm(double tickTime, int run_count, const FunctionObject& fn)
    : StopWatch(), _delegate(fn), _tickTime(tickTime), _run_count(run_count < -1 ? -1 : run_count) { /* DO NOTHING */ }

template<class FunctionObject>
Alarm<FunctionObject>::~Alarm() {
    if(_isRunning) Stop();
}

template<class FunctionObject>
FunctionObject Alarm<FunctionObject>::Tick() {
    if(IsRunning() == false) return _delegate;

    if(GetElapsedTimeInSeconds() >= _tickTime) {
        Reset();
        if(_run_count == 0) return _delegate;
        _delegate();
        if(_run_count > -1) --_run_count;
        Start();
    }
    return _delegate;
}

Will this work if the user attempts to pass in a lambda or std::function?

If not, it doesn't seem simply adding a constructor that takes a lambda (is that even possible?) or std::function will work either.


Solution

  • Since it's a template that's parameterised on the function object's class, yes, it should work with all callable objects.