Home > Net >  How to call a polymorphic method in a thread object?
How to call a polymorphic method in a thread object?

Time:09-17

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);
    }
}

What is the right way to call the do_work() method in the thread?

CodePudding user response:

The polymorphism should just work, because a pointer to a virtual member function will always behave polymorphically when invoked. There are only two changes required to make your program correct:

  1. You have to write worker.get() when creating the thread. This is because the pointer to member function Base::do_work is "invokable" with an argument that is a pointer to Base, but you can't "pass" a smart pointer to it directly.
  2. You have to remember to either detach or join the threads before the end of main.
  • Related