简体   繁体   中英

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> ?

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM