lundi 30 août 2021

How to call a polymorphic function in a thread object

struct Base {
    virtual void do_work()=0;
};

struct Derived_A : Base{
    void do_work() override {
        //work A
    }
};

struct Derived_B : Base{
    void do_work() override {
        //work B
    }
};

int main() {
    std::vector<std::unique_ptr<Base>> workers;
    workers.emplace_back(std::unique_ptr<Base>(new Derived_A()));
    workers.emplace_back(std::unique_ptr<Base>(new Derived_B()));
    
    std::vector<std::thread> threads;
    for (const auto& worker : workers) {
            //Compile error
            //expecting Derived_A and Derived_B do_work functions to be called respectively
            threads.emplace_back(&Base::do_work, worker);
    }
    
}

From the code snippet above, what is the right way to call the do_work function in the thread? It's a straightforward question but Stackoverflow requires me to add more text to my question so I'm writing this.

Aucun commentaire:

Enregistrer un commentaire