How to define different types for the same class in C++

前端 未结 4 1527
臣服心动
臣服心动 2020-11-28 22:51

I would like to have several types that share the same implementation but still are of different type in C++.

To illustrate my question with a simple example, I woul

4条回答
  •  佛祖请我去吃肉
    2020-11-28 23:12

    Use templates, and use a trait per fruit, for example:

    struct AppleTraits
    {
      // define apple specific traits (say, static methods, types etc)
      static int colour = 0; 
    };
    
    struct OrangeTraits
    {
      // define orange specific traits (say, static methods, types etc)
      static int colour = 1; 
    };
    
    // etc
    

    Then have a single Fruit class which is typed on this trait eg.

    template 
    struct Fruit
    {
      // All fruit methods...
      // Here return the colour from the traits class..
      int colour() const
      { return FruitTrait::colour; }
    };
    
    // Now use a few typedefs
    typedef Fruit Apple;
    typedef Fruit Orange;
    

    May be slightly overkill! ;)

提交回复
热议问题