(Using C++17)
I have a situation where I need to iterate through a list of subclasses:
class S {}
class A : S {}
class B : S {}
class C : S {}
for (int i = 0; i < 3; i++) {
    shared_ptr<S> p;
    if (i == 0) {
        p = make_shared<A>();
    }
    else if (i == 1) {
        p = make_shared<B>();
    }
    else if (i == 2) {
        p = make_shared<C>();
    }
    // Do something with 'p'
}
This is quite ugly. I would much rather do something like this:
class S {}
class A : S {}
class B : S {}
class C : S {}
for (S subclass_type : {A, B, C}) {
    shared_ptr<S> p = make_shared<subclass_type>();
    // Do something with 'p'
}
Is this possible in C++? Can you initialize a template class from a variable type? (Not just shared_ptr.)
Aucun commentaire:
Enregistrer un commentaire