错误(活动)E0289 没有构造函数“std::thread::thread”的实例与参数列表匹配
#ifndef TIMER_H
#define TIMER_H
#include <thread>
#include <chrono>
class Timer
{
std::thread Thread;
bool Alive = false;
long CallNumber = -1L;
long repeat_count = -1L;
std::chrono::milliseconds interval = std::chrono::milliseconds(0);
std::function< void(void) > funct = nullptr;
void SleepAndRun()
{
std::this_thread::sleep_for(interval);
if (Alive)
Function()();
}
void ThreadFunc()
{
if (CallNumber == Infinite)
while (Alive)
SleepAndRun();
else
while (repeat_count--)
SleepAndRun();
}
public:
static const long Infinite = -1L;
Timer(){}
Timer(const std::function<void(void)> &f) : funct (f) {}
Timer(const std::function<void(void)> &f,
const unsigned long &i,
const long repeat = Timer::Infinite) : funct(f),
interval(std::chrono::milliseconds(i)),
CallNumber(repeat) {}
void Start(bool Async = true)
{
if (isAlive())
return;
Alive = true;
repeat_count = CallNumber;
if (Async)
Thread = std::thread(ThreadFunc, this);// <- There is an error
else
this->ThreadFunc();
}
void Stop()
{
Alive = false;
Thread.join();
}
void SetFunction(const std::function<void()> &f)
{
funct = f;
}
bool isAlive() const { return Alive; }
void RepeatCount(const long r)
{
if (Alive)
return;
CallNumber = r;
}
long GetLeftCount() const { return repeat_count; }
long RepeatCount() const { return CallNumber; }
void SetInterval(const unsigned long &i)
{
if (Alive)
return;
interval = std::chrono::milliseconds(i);
}
unsigned long Interval() const { return interval.count(); }
const std::function<void(void)> &Function() const
{
return funct;
}
};
#endif // !TIMER_H
Run Code Online (Sandbox Code Playgroud)
严重性代码说明项目文件行抑制状态错误 C3867 'Timer::ThreadFunc':非标准语法;使用“&”创建指向成员 53 的指针
第 53 行错误
有人可以解释这个错误是什么意思吗?
ThreadFunc是非静态成员函数,它需要this指针。
最简单的修复方法是在 lambda 中传递:
Thread = std::thread([this] { this->ThreadFunc(); });
Run Code Online (Sandbox Code Playgroud)
或者正如@Some 程序员所指出的那样:
Thread = std::thread(&Timer::ThreadFunc, this);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7864 次 |
| 最近记录: |