Last active
February 26, 2016 17:33
-
-
Save kreshikhin/2d7e2257242f27937bbf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <iostream> | |
class Fruit{ | |
public: | |
std::string variety; | |
public: | |
std::string virtual GetVariety() { return variety; }; | |
}; | |
class Apple : public Fruit{ | |
public: | |
Apple(std::string variety) { this->variety = variety; }; | |
}; | |
class Pear : public Fruit{ | |
public: | |
Pear(std::string variety) { this->variety = variety; }; | |
}; | |
template <class T> | |
std::vector<T> GetSelectedFruits(std::vector<Fruit*> fruits){ | |
std::vector<T> result; | |
for(size_t i = 0; i < fruits.size(); ++i) { | |
T fruit = dynamic_cast<T>(fruits[i]); | |
if(!fruit) continue; | |
result.push_back(fruit); | |
} | |
return result; | |
} | |
int main(){ | |
std::vector<Fruit*> fruits; | |
fruits.push_back(new Apple("Macintosh")); | |
fruits.push_back(new Pear("Bartlett")); | |
fruits.push_back(new Apple("Fuji")); | |
fruits.push_back(new Pear("Concorde")); | |
fruits.push_back(new Apple("Gala")); | |
std::vector<Apple*> apples = GetSelectedFruits<Apple*>(fruits); | |
std::cout << "the count of apples: " << apples.size() << std::endl; | |
for(size_t i = 0; i < apples.size(); ++i) { | |
std::cout << apples[i]->GetVariety() << std::endl; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment