3

Error (active) E0289 no instance of constructor "std::thread::thread" matches the argument list

#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

Severity Code Description Project File Line Suppression State Error C3867 'Timer::ThreadFunc': non-standard syntax; use '&' to create a pointer to member 53

error on 53th line

Can someone explain what means this error?

lloydpick
  • 1,638
  • 1
  • 18
  • 24
Hypergloom AO
  • 33
  • 1
  • 1
  • 4

1 Answers1

9

ThreadFunc is non-static member function it needs this pointer.

The easiest way to fix is to pass is in lambda:

Thread = std::thread([this] { this->ThreadFunc(); });

or as @Some programmer dude pointed out just:

Thread = std::thread(&Timer::ThreadFunc, this);
Mihayl
  • 3,821
  • 2
  • 13
  • 32