Search code examples
c++c++11lambdapocopoco-libraries

C++ template for Runnable function


I am writing a library for thread management using C++ for my app and as part of the same I am trying to write a template class that takes a FunctionPointer to be executed inside the run function. I am a Java developer and trying to visualize as follows:

class MyRunnable : public Runnable {

    public:
        MyRunnable(fp)
        {
            mFp = fp;
        }

    private:

    FunctionPointer mFp;

    // Will be called by the thread pool using a thread
    void run() 
    {
         mFp();
    }

}

class ThreadManager {

    public:
        void execute(MyRunnable runnable) {
            executeOnAThreadPool(runnable);
        }

}

Since I am not fluent with C++ syntax, I am finding hard to get the constructor defined to take a FunctionPointer as argument with variable number of arguments for the FunctionPointer. Something like:

MyRunnable(Fp fp, Args... args)

Can someone please help me defining the constructor for MyRunnable class above. Thanks.


Solution

  • Not sure... but seems to me that you're looking something as

    class MyRunnable
     {
       private:
          std::function<void()> mF;
    
       public:       
          template <typename F, typename ... Args>
          MyRunnable (F && f, Args && ... args)
           : mF{ [&f, &args...](){ std::forward<F>(f)(std::forward<Args>(args)...); } }
           { }
    
          void run ()
           { mF(); }
     };
    

    The following is a full compiling example

    #include <iostream>
    #include <functional>
    
    class MyRunnable
     {
       private:
          std::function<void()> mF;
    
       public:       
          template <typename F, typename ... Args>
          MyRunnable (F && f, Args && ... args)
           : mF{ [&f, &args...](){ std::forward<F>(f)(std::forward<Args>(args)...); } }
           { }
    
          void run ()
           { mF(); }
     };
    
    void foo (int a, long b, std::string const & c)
     { std::cout << "executing foo() with " << a << ", " << b << ", " << c << '\n'; }
    
    int main ()
     {
       MyRunnable  mr{foo, 1, 2l, "three"};
    
       std::cout << "before run" << '\n';
    
       mr.run();
    
     }
    

    that prints

    before run
    executing foo() with 1, 2, three