Run Code
|
API
|
Code Wall
|
Users
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Identifying polimorphic types without using RTTI or type mappings
//Title of this code //g++ 4.8.2 #include <iostream> #include <vector> #include <algorithm> #include <memory> struct DieselCar; struct PetrolCar; struct Car { virtual const char * getName() const = 0; virtual bool hasType(const Car*) const { return true; } virtual bool hasType(const DieselCar*) const { return false; } virtual bool hasType(const PetrolCar*) const { return false; } }; struct DieselCar : public Car { const char * getName() const { return "DieselCar"; } bool hasType(const DieselCar*) const { return true; } }; struct PetrolCar : public Car { const char * getName() const { return "PetrolCar"; } bool hasType(const PetrolCar*) const { return true; } }; template<class T> struct HasType { bool operator()(const std::shared_ptr<Car> sec) const { return sec->hasType(static_cast<T*>(NULL)); } }; int main() { std::vector<std::shared_ptr<Car>> securities; securities.push_back(std::make_shared<DieselCar>()); securities.push_back(std::make_shared<PetrolCar>()); securities.push_back(std::make_shared<DieselCar>()); securities.push_back(std::make_shared<DieselCar>()); securities.push_back(std::make_shared<PetrolCar>()); securities.push_back(std::make_shared<DieselCar>()); securities.push_back(std::make_shared<PetrolCar>()); securities.push_back(std::make_shared<DieselCar>()); std::cout << securities.size() << std::endl; securities.erase(std::remove_if(securities.begin(), securities.end(), HasType<DieselCar>()), securities.end()); std::cout << securities.size() << std::endl; }
run
|
edit
|
history
|
help
0
Please
log in
to post a comment.
read_write_lock_acc
3 and 7 in a row
Backtracking_simple
Test 12(2020)
Proyecto 1
CodeChef P1 MATMIN1
template
Sort array of 0's and 1's
variadic template
325324
Please log in to post a comment.