Search code examples
c++c++11stdthread

Running a thread using a variable type of std::function


I would like to launch a std::function type in a separate thread. My code currently looks like this :

struct bar
{
    std::function<void(int,int)> var;
};

struct foo
{
    bar* b;

    foo()
    {
        std::thread t(b->var); //Error attempt to use a deleted function
    }
};

Why am I getting attempt to use a deleted function here ?


Solution

  • Your variable b->var is a function that takes two parameters. You need to send these parameters to make it work.

    struct bar
    {
      std::function<void(int,int)> var;
    };
    
    struct foo
    {
       bar* b;
       foo()
       {
          std::thread t(b->var, 76, 89); // will call b->var(76, 89)
       }
    };