1

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.

  • Form 1: Exactly I don't want my IBase have any non-virtual function.
  • Form 2: There's a strange expression &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.

StephanXu
  • 49
  • 5
  • (this is specific to the code i deal with and not a general rule) Generally the interfaces say 'IParent' contain ONLY declarations of virtual/ pure virtual functions say ('virtualFunc'). Then derive classes from the interface class say DeriveClass1 and DeriveClass2 which have their own implementations of the 'virtualFunc' . Now, have a base class pointer point to one of the derived class objects and call the function using that pointer. So, at runtime the respective derived class function gets called depending on the type of object. – dorKKnight Jul 25 '19 at 04:46

2 Answers2

2

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.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
1

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).

Mario The Spoon
  • 4,799
  • 1
  • 24
  • 36
  • 2
    And why on earth do you want to allocate `std::thread` on the heap? – r3mus n0x Jul 25 '19 at 05:38
  • 1
    So who will release the thread object? I personally think this probably makes the problem more complex. – StephanXu Jul 25 '19 at 07:10
  • I was not watching that aspect (since not really part of the Q) - also when do your threads get destroyed? Fixing my de-allocation problem can be done using auto_ptr or unique_ptr or other instance management constructs. – Mario The Spoon Jul 26 '19 at 08:55