fork download
  1. #include <memory>
  2. #include <string>
  3. #include <unordered_map>
  4. #include <iostream>
  5. #include <cstdlib>
  6.  
  7. using namespace std;
  8.  
  9.  
  10. struct Animal {
  11. virtual void say(ostream &ostr) const = 0;
  12. };
  13.  
  14. struct Dog: public Animal {
  15. virtual void say(ostream &ostr) const {
  16. ostr << "Bark!";
  17. }
  18. };
  19.  
  20. struct Cat: public Animal {
  21. virtual void say(ostream &ostr) const {
  22. ostr << "Meow!";
  23. }
  24. };
  25.  
  26. typedef unordered_map<string, unique_ptr<Animal>> AnimalMap;
  27.  
  28. static const char *ANIMAL_ENV = "ANIMAL";
  29. static const char *ANIMAL_DEFAULT = "Dog";
  30.  
  31. int main(int, char const *[])
  32. {
  33. static const AnimalMap animal_map = []() {
  34. AnimalMap res;
  35. res.emplace("Dog", make_unique<Dog>());
  36. res.emplace("Cat", make_unique<Cat>());
  37. return res;
  38. }();
  39.  
  40. const char *animal = getenv(ANIMAL_ENV);
  41. if (animal == nullptr) {
  42. animal = ANIMAL_DEFAULT;
  43. }
  44.  
  45. auto hit = animal_map.find(animal);
  46. if (hit != animal_map.cend()) {
  47. hit->second->say(cout);
  48. cout << endl;
  49. } else {
  50. cerr << "Error: Animal not found: " << animal << endl;
  51. }
  52.  
  53. return 0;
  54. }
  55.  
Success #stdin #stdout 0s 15248KB
stdin
Standard input is empty
stdout
Bark!