0

I am a new in c++ maybe I miss something, but actually what I need to do is: I have a class that processing something in other thread, during this processing I need that it invoke a callback for progress.

How I see I can do it, I need to declarate pointer (maybe shared_ptr) for my callback function as a class member, than I have a setter in order to pass pointer to callback and then I can use it. A few issues here are how to pass it correctly? How to invoke pointer on function?

My implementation is:

class RobocopyCopy
{
    //Public members
public:
    typedef std::function<void(int)> TVoidIntCallback;

    RobocopyCopy * set_monitoring_done_callback(TVoidIntCallback monitoring_done_callback)
    {
       m_pMonitoring_done_callback = &monitoring_done_callback;
       return this;
    }

    //This method executes in background
    void execute()
    {
        ...
        //and here I need to invoke my callback
        (TVoidIntCallback *)m_pMonitoring_done_callback(777); //but this is not correct


private:
    TVoidIntCallback * m_pMonitoring_done_callback;


...
}

and final implementation of this should be like this (I think) :

RobocopyCopy robocopy;
    robocopy.set_monitoring_done_callback([this](int my_progress) {
        printf("Progress is :: %d", my_progress);
    });

So, as I mentioned above questions is :

  1. how to pass this function callback as a lambda and save in Robocopy class as a pointer
  2. How to invoke this function correctly, because this (TVoidIntCallback *)m_pMonitoring_done_callback(777); doesn't work.
1
  • 3
    m_pMonitoring_done_callback shouldn't be a pointer. Drop the star, make it TVoidIntCallback m_pMonitoring_done_callback; Then call it simply as m_pMonitoring_done_callback(777); Commented May 31, 2020 at 14:14

1 Answer 1

1

I am using VC++ I hope this code will be successful for you.

class RobocopyCopy
{
   typedef std::function<void(int)> TVoidIntCallback;
   TVoidIntCallback evnt;
   public:

   RobocopyCopy* set_monitoring_done_callback(TVoidIntCallback 
   monitoring_done_callback)
   {
     //set callBack function from out side.
     evnt = monitoring_done_callback;
     return this;
   }

    void execute() {
       //invoke your callBack
      evnt(1000000);
    }
};

int main()
{
   RobocopyCopy obj;
   obj.set_monitoring_done_callback([](int data) {
    std::cout << data << "\n";
    })->execute();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.