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

前端 未结 4 1529
臣服心动
臣服心动 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:02

    A common technique is to have a class template where the template argument simply serves as a unique token (“tag”) to make it a unique type:

    template 
    class Fruit {
        int p;
    public:
        Fruit(int p) : p(p) { }
        int price() const { return p; }
    };
    
    using Apple = Fruit;
    using Banana = Fruit;
    

    Note that the tag classes don’t even need to be defined, it’s enough to declare a unique type name. This works because the tag isn’s actually used anywhere in the template. And you can declare the type name inside the template argument list (hat tip to @Xeo).

    The using syntax is C++11. If you’re stuck with C++03, write this instead:

    typedef Fruit Apple;
    

    If the common functionality takes up a lot of code this unfortunately introduces quite a lot of duplicate code in the final executable. This can be prevented by having a common base class implementing the functionality, and then having a specialisation (that you actually instantiate) that derives from it.

    Unfortunately, that requires you to re-implement all non-inheritable members (constructors, assignment …) which adds a small overhead itself – so this only makes sense for large classes. Here it is applied to the above example:

    // Actual `Fruit` class remains unchanged, except for template declaration
    template 
    class Fruit { /* unchanged */ };
    
    template 
    class Fruit : public Fruit {
    public:
        // Should work but doesn’t on my compiler:
        //using Fruit::Fruit;
        Fruit(int p) : Fruit(p) { }
    };
    
    using Apple = Fruit;
    using Banana = Fruit;
    

提交回复
热议问题