为使用函数对象而编写的类是否也可以使用lambda或std::函数类型?
Can a class written to work with a function object also work with a lambda or std::function type?
我已经编写了一个模板类来处理无参数的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
也可以工作。
因为它是一个模板,在函数对象的类上参数化,是的,它应该与所有可调用的对象一起工作。
相关文章:
- void 函数可以传递值参数吗?
- C++中的双边友语函数:如何使其编译?
- 为什么使用析构函数会使类不可复制?
- 当没有显式关键字与单参数构造函数一起使用时,编译器可以发出警告
- 有没有一种技术可以使虚函数在所有派生类中强制重写?
- 有没有一种方法可以使全局函数/静态成员函数一次可呼出
- 编写一个可以使二维数组平坦的函数
- 是否可以使函数模板从函数引用中获取“decltype”
- 是否可以使函数模板对不适当的类型而不是错误执行默认操作
- 是否可以使程序的执行跳过 fprintf-语句/如何创建我自己的 fprintf 函数
- 是否有一个内置函数可以使线程的一部分不并发运行
- 是否有某种方法可以使C ++类中的一个函数在不同的线程中运行
- 是否可以使函数接受给定参数的多种数据类型
- 有哪些技巧可以使包含大量计算的函数简洁
- 当我向只接受无符号整数的函数提供有符号整数时,是否有一种方法可以使GCC警告我?
- 可以声明一个c++函数,使其返回值不能被忽略吗?
- 我可以使函数"外部"c""吗?
- 是否有一种方法可以使c++析构函数被急切地调用
- 在 c++ 中是否有任何方法可以使一个类的函数,每个类的对象都为该函数做不同的事情?
- 是否可以使函数对于常量参数或变量参数的行为不同