Very interesting class template specialisation as well as usage of enumeration classes in cpp

 #include <iostream>

using namespace std;
enum class Fruit { apple, orange, pear };
enum class Color { red, green, orange };

template <typename T> struct Traits;
 
 //Variadic function template is implemented below
//  template<typename foo,typename... bar>
//  void boo(foo obj1,bar... obj2){
     
//  }
// Define specializations for the Traits class template here.
//Don't ever give me any advice in the form of comments at all, I am not like others fool!
template<>
struct Traits<Fruit> {
    public:
 static string name(int n){
      if((int)Fruit::apple==n){
          return "apple";
      }
      if((int)Fruit::orange==n){
          return "orange";
      }
      if((int)Fruit::pear==n){
          return "pear";
      }
      return "unknown";
  }  
};

template<>
struct Traits<Color>{
  public:
 static string name(int n){
      if((int)Color::green==n){
          return "green";
      }
      else if((int)Color::orange==n){
          return "orange";
      }
      else if((int)Color::red==n){
          return "red";
      }
      return "unknown";
  }  
};
//A reminder for how a class template specialisation works 

// template<class T>
// class himesh{
//   public:
//   T x;  
// };
// template<>
// class himesh<string>{
//     public:
//     string str;
// };

int main()
{
    int t = 0; std::cin >> t;

    for (int i=0; i!=t; ++i) {
        int index1; std::cin >> index1;
        int index2; std::cin >> index2;
        cout << Traits<Color>::name(index1) << " ";
        cout << Traits<Fruit>::name(index2) << "\n";
    }
}

Comments

Popular Posts