C++ 编写用于处理函数对象的类是否也可以处理lambda或std::function类型?

C++ 编写用于处理函数对象的类是否也可以处理lambda或std::function类型?,c++,c++11,lambda,functor,std-function,C++,C++11,Lambda,Functor,Std Function,我编写了一个模板类,用于处理无参数void返回函数对象: //...Class declaration here... template<class FunctionObject> Alarm<FunctionObject>::Alarm(const FunctionObject& fn) : StopWatch(), _delegate(fn), _tickTime(1.0), _run_count(-1) { /* DO NOTHING */ }

我编写了一个模板类,用于处理无参数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;
}
//…此处的类声明。。。
模板
报警::报警(常量函数对象和fn)
:StopWatch(),_delegate(fn),_tickTime(1.0),_run_count(-1){/*什么都不做*/}
模板
报警::报警(双计时、常量函数对象和fn)
:StopWatch(),_delegate(fn),_tickTime(tickTime),_run_count(-1){/*什么都不做*/}
模板
报警::报警(双计时、整数运行计数、常量函数对象和fn)
:StopWatch(),_delegate(fn),_tickTime(tickTime),_run_count(run_count<-1?-1:run_count){/*什么都不做*/}
模板
警报::~Alarm(){
如果(_正在运行)停止();
}
模板
FunctionObject报警::勾选(){
如果(IsRunning()==false)返回_委托;
如果(GetElapsedTimeInSeconds()>=\u tickTime){
重置();
如果(_run_count==0)返回_delegate;
_委托();
如果(\u运行\u计数>-1)——\u运行\u计数;
Start();
}
返回代表;
}
如果用户试图传入lambda或
std::function
,这是否有效


如果不是的话,它似乎不是简单地添加一个接受lambda的构造函数(这可能吗?)或者
std::function
也会起作用。

因为它是一个在函数对象的类上参数化的模板,是的,它应该可以处理所有可调用的对象。

我怀疑对于非void返回的对象,返回类型将被忽略,但如果传入的lambda/std::函数有参数,是否会出现错误?@Casey:为什么会“忽略”?返回类型是函数类型的一部分。我看不出这里有什么问题。当然,这可能只是因为我们不知道什么是
\u delegate
。为什么不试试看??有没有什么特别的原因不使用尾部默认参数?
std::function
和lambda是functor/function对象。它们没有什么特别之处(lambda是缩写,仅此而已)。请注意,标准库的先例是通过值而不是常量引用传递“callables”。还要注意的是,虽然您在这里的使用看起来很好,但在许多情况下,前导
\u
是被禁止的,一个简单的规则就是完全避免这样的前导
\u