为使用函数对象而编写的类是否也可以使用lambda或std::函数类型?

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

本文关键字:函数 可以使 lambda 类型 std 对象 是否      更新时间:2023-10-16

我已经编写了一个模板类来处理无参数的void返回函数对象:

//...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;
}

如果用户试图传入lambda或std::function,这是否有效?

如果没有,似乎不简单地添加一个接受lambda的构造函数(甚至可能吗?)或std::function也可以工作。

因为它是一个模板,在函数对象的类上参数化,是的,它应该与所有可调用的对象一起工作。