开发者

class containing a generic type of a child

Is there any possible way that a generic type can be used to contain a child of a base class.

From the assignment given to开发者_JS百科 me, I am to create something similar to the following in structure.

template <class T>
class Fruit {
  private:
    int count;
    int location_id;
    T type;
  public:
    virtual void displayInfo();
};

class Apple : private Fruit<Apple> {
  private:
    int variety;
  public:
    void displayInfo() {
        printf("Location %i has %i of %s in stock", location_id, count, variety);
    }
};

Fruit<Apple> appleinventory[SIZE];

Basically, I think you can't have a template generic type be the same as a derived class. Am I wrong? Is there something similar that would possibly work?

Update: For the assignment, I believe we are to use inheritance to show use of virtual functions. I've updated the code above. I think this would work, but does NOT need templates to be successful. We have not covered any advanced, redundant inheritance methods in class.


This is perfectly fine, in principle.

Read up about Curiously Recurring Template Pattern (CRTP) for more info on usage of derived class as the instantiating type in a class template that is its base, esp the example about static polymorphism which should look 'curiously' familiar.

template <class Derived> struct Base
{
    void interface()
    {
        // ...
        static_cast<Derived*>(this)->implementation();
        // ...
    }

    static void static_func()
    {
        // ...
        Derived::static_sub_func();
        // ...
    }
};

struct Derived : Base<Derived>
{
    void implementation();
    static void static_sub_func();
};


Ignoring questions of why you want to do this....you can get some of the way by doing this following:

template <class T> class Fruit 
{
private:
    int count;
    int location_id;
    T* type;
};

class Apple : private Fruit<Apple> 
{
private:
    int seeds;
    bool red;
};

Fruit<Apple> appleinventory[SIZE];

Note the T* type is now a pointer to Apple rather than an instance of Apple.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜