mercredi 29 novembre 2017

Create distinct type for class with specific member variable value

Given a class that have some enum that defines a type of the class, like in following example:

class Fruit {
 public:

   enum class FruitType {
      AppleType = 0,
      OrangeType = 1,
      BananaType = 2,
   };
   Fruit(FruitType type) : type_(type) {}
   FruitType fruit_type() const { return type_; }

 private:
   FruitType type_;
};

Would it be possible to somehow define a distinct type for Fruit with each of the specific enum values:

class Apple   // Fruit with FruitType = AppleType
class Orange  // Fruit with FruitType = OrangeType
class Banana  // Fruit with FruitType = BananaType

so that 3 classes Apple, Orange and Banana are distinct types.

My question is somewhat similar to How to define different types for the same class in C++, except that I want to explicitly store information about class type as enum member variable in the class, and to have a common base class for all distinct types.

What would be the most efficient way to do that?

Aucun commentaire:

Enregistrer un commentaire