HackerRank C++ Class Template Specialization




You are given a main function which reads the enumeration values for two different types as input, then prints out the corresponding enumeration names. Write a class template that can provide the names of the enumeration values for both types. If the enumeration value is not valid, then print unknown.



  1. #include <iostream>
  2. using namespace std;
  3. enum class Fruit { apple, orange, pear };
  4. enum class Color { red, green, orange };
  5. template <typename T> struct Traits;
  6. // Define specializations for the Traits class template here.
  7. template <>
  8. struct Traits<Fruit>{
  9. static string name(int index){
  10. switch(index){
  11. case 0:return "apple";
  12. case 1: return "orange" ;
  13. case 2: return "pear";
  14. }
  15. return "unknown";
  16. }
  17. };
  18. template <>
  19. struct Traits<Color>{
  20. static string name(int index){
  21. switch(index){
  22. case 0:return "red";
  23. case 1: return "green" ;
  24. case 2: return "orange";
  25. }
  26. return "unknown";
  27. }
  28. };
  29. int main()
  30. {
  31. int t = 0; std::cin >> t;
  32. for (int i=0; i!=t; ++i) {
  33. int index1; std::cin >> index1;
  34. int index2; std::cin >> index2;
  35. cout << Traits<Color>::name(index1) << " ";
  36. cout << Traits<Fruit>::name(index2) << "\n";
  37. }
  38. }
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]


donate a cup of tea :)


Join Our Facebook Group

Share this solution






codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube