Passing member function as a parameter...

I want to pass(from one class to another) a member function as a parameter and then for that member function to be called in a separate thread.

This seems to be a common error and given solutions involve making the member function's class object available to the calling class or making the member function static, however I cant seem to implement any of these solutions into the code below.

Can I request that any answers include a working version of the code below.

Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <thread>
#include <iostream>

class class1 {

public:
    class1::class1() : t1() { }

    std::thread* t1;

    template<typename Fn>
    void func1(Fn);

};

template<typename Fn>
void class1::func1(Fn func_)
{
    this->t1 = new std::thread(&func_);
}


class class2 {

public:
    class2::class2() :  c1() { }

    class1 c1;

    void class2::func1()
    {
        c1.func1(&class2::func2);
    }

    void class2::func2()
    {
        std::cout << "Woof" << std::endl;
    }

};


1
2
Error C2893 Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...) noexcept()'
Error C2672 'std::invoke': no matching overloaded function found
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <functional> //for std::bind()
#include <iostream>
#include <thread>

class class1 {
public:
  class1() {}
  std::thread *t1; //¿is a pointer really necessary?
  template <typename Fn> void func1(Fn);
};

template <typename Fn> void class1::func1(Fn func_) {
  this->t1 = new std::thread(func_);
  t1->join();
}

class class2 {
public:
  class2() : c1() {}
  class1 c1;
  void func1() {
    c1.func1(std::bind(&class2::func2, this));
  }
  void func2() { std::cout << "Woof " << std::endl; }
};

int main() {
  class2 foo;
  foo.func1();
}
to call a member function you need an object (which is kind of what the error message is saying)
not sure if bind() is the best, or what's the difference between binding this or *this
Last edited on
Thank you very much, was pulling my hair out with this.
Topic archived. No new replies allowed.