Вопрос

I'm trying to create threads of member functions that are accessed via pointers to objects.

So I have

AbstractBaseClass* object1 = new ChildClass;

then I want to make a thread of object1->foo();

so I try

thread t1(object->foo(variable));

but it says "no instance of constructor std::thread::thread matches the argument list arguments types are void." When I hover over object1.

On compile it says,

error C2664: 'std::thread::thread(const std::thread &)' : cannot convert argument 1 from 'void' to 'std::thread &&'
1>          Expressions of type void cannot be converted to other types

I've tried making the foo() a type thread (not sure if that is correct) and it gets rid of the error but instead gives, no return for for type thread of which I am not returning anything cause I don't know what to return for thread.

How do I tackle this?

It isn't homework, just a learning experience for me.

Это было полезно?

Решение

std::thread follows the syntax of std::bind, so the correct invocation is

std::thread t(&AbstractBaseClass::foo, object, variable)

The first one is called a pointer to member function. The above will copy by value the parameters passed to it. If you need pass by reference, use std::ref, like

std::thread t(&AbstractBaseClass::foo, object, std::ref(variable))

Remember the keep the lifetime of variable longer than the thread in that case.

Другие советы

Just take a look at a std::thread man page. You'll see that the constructor you need looks like it:

template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );

So, replace thread t1(object->foo(variable)); by thread t1(&class::foo, object, variable);

This answer

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top