Olzhabay Olzhabay - 1 month ago 16
C++ Question

Does std::future support polymorphism?

Does std::future in c++ support polymorphism?
So, if to store

child_class
in
future<parent_class>
, can I after get it after by
dynamic_cast<child_class>
?

Answer

Providing you use a reference or a pointer (probably obvious since it'll fail to compile otherwise)... Yes.

#include <iostream>
#include <future>
using namespace std;
struct Parent {
    virtual void a() { cout << "I am parent"; }
};
struct Child : Parent {
    virtual void a() { cout << "I am child"; }
};

Child g_c; //just some global for the purposes of the example

int main() {
    std::future<Parent&> p = async(launch::async, []() -> Parent& { return g_c; });
    auto c = dynamic_cast<Child&>(p.get());
    c.a();
    return 0;
}

code result here: http://ideone.com/4Qmjvc