Reputation: 5165
I know there exists this question and this one as well. I have gone through both of them and haven't been able to solve my problem. I was able to run examples for class member functions that take zero arguments, but was not able to deduce what the constructor for the thread would look like in case the member function had arguments.
I have a class A. A has a member function f that takes 2 parameters p1 and p2. I have instantiated an object a of class A. I want to call the function f in a thread.
From cppreference.com :
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
is how I must write the constructor.
I am having trouble deciphering the above definition. How can I call a.f(p1,p2) defined as
void A::f(int p1, int p2)
in a thread ?
Upvotes: 0
Views: 1565
Reputation: 34538
Simply pass the arguments:
std::thread t(&A::f, &bar, p1, p2);
t.join();
Note: Notice that we are passing the address of your bar
object, otherwise the thread constructor would copy your object. By doing this you have to guarantee that your object outlives your thread. Note, that the same is true for the other arguments. In case of the arguments you can simply use std::ref
.
In general, as mentioned in my other post, the std::thread
constructor is defined in terms of the INVOKE
definition (§20.8.2.1):
Define INVOKE (f, t1, t2, ..., tN) as follows:
- (t1.*f)(t2, ..., tN) when f is a pointer to a member function of a class T and t1 is an object of type T or a reference to an object of type T or a reference to an object of a type derived from T;
- ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a class T and t1 is not one of the types described in the previous item;
- t1.*f when N == 1 and f is a pointer to member data of a class T and t 1 is an object of type T or a
reference to an object of type T or a reference to an object of a
type derived from T;- (*t1).*f when N == 1 and f is a pointer to member data of a class T and t 1 is not one of the types described in the previous item;
- f(t1, t2, ..., tN) in all other cases.
Upvotes: 7