I have a IBase
class and a Child
class. I need to call different proc
function in different child class. I'm not sure which form below is actually right, maybe neither XD.
IBase
have any non-virtual function. &IBase::proc
could make some misunderstanding. class IBase
{
public:
virtual void proc() = 0;
auto createBind()
{
return bind(&IBase::proc, this);
}
};
class Child :public IBase
{
public:
void proc() override
{
cout << "Hello World" << endl;
}
};
int main()
{
IBase* pointer = new Child;
//form 1
thread th(pointer->createBind());
th.join();
//form 2
thread th2(&IBase::proc, pointer);
th2.join();
cout << "Finish" << endl;
return 0;
}
I'm wondering how do you guys solve this circumstance in a real project.
I would use form 3 :-) :
thread* th3 = pointer->start();
th3->join();
with start
in IBase
as:
thread* start()
{
thread* t = new thread(createBind());
return t;
}
Which would in my opinion hide more details of the implementation and give the caller the API he expects (start a thread).
The most idiomatic and robust way is probably this
std::thread t([=]{pointer->proc();});
No bind, no extraneous helper member function, no weird syntax with redundant mention of the class name.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.