views:

55

answers:

2

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 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.

A: 

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.

Damyan
A: 

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();
};
Steve Townsend
This is interesting and shows it can happen. However, the way it was described to me won't work in this manner...
mike_b