Cóż, ostatnio pojawiło się jeszcze jedno standardowo dostępne rozwiązanie. Jeśli masz nowoczesny kompilator, stosujesz typ std::variant. Wystarczy włączyć nagłówek <variant>. Krótki przykład:
#include <variant>
#include <iostream>
class Apple {
public:
void info() const {
std::cout << "I'm apple.\n";
}
};
class Cherry {
public:
void info() const {
std::cout << "I'm cherry.\n";
}
};
int main() {
std::variant<Apple, Cherry> table[] = {
Apple(), Apple(), Cherry(), Apple()
};
for(const auto& obj: table) {
try {
std::get<Apple>(obj).info();
} catch(const std::bad_variant_access&) {
std::get<Cherry>(obj).info();
}
}
}
Osobiście wybrał bym rozwiązanie z std::unique_ptr.