Kit
Kit

Reputation: 51

Storing template type to cast Base back down to Derived<T>

So I have these classes:

class Base {

};
template <typename T>
class Derived<T>: public Base {

};

class util {
    public:
        template <typename T>
        void add(Derived<T> arg) {
           vec.push_back(arg);
        } 
        
        void start() {
            //cast back down to Derived<T>
        }
  
   private:
       std::vector<Base> vec;
};

In start() I want to cast it back down to Derived<T> but since the T can be anything, I can't cast it without the type. I'm wondering if there was to store the first element of vec's type information in like a typedef or something so that I can use that in start()

Upvotes: 1

Views: 143

Answers (1)

Coral Kashri
Coral Kashri

Reputation: 3506

First of all you have a syntax issue:

template <typename T>
class Derived<T>: public Base { // Won't compile, the class name is Derived, and it doesn't suppose to get specialized by T type
};

The right way:

template <typename T>
class Derived : public Base {};

For your issue, you don't need to convert it back to the derived type, you just need to make your vector a vector of pointers to Base class (and in the insertion function, accept the Derived type as a reference, to pass it's address to the vector).
Note: in the implementation you'll see that I passed a shared_ptr- it's to make the ownership of the address obvious, when you use shared_ptr instead of unsafe pointers in your vector (Thanks to @idclev463035818 for the note).

class util {
public:
    template <typename T>
    void add(std::shared_ptr<Derived<T>> arg) {
        vec.push_back(arg);
        // vec.push_back(&arg); // In case that you don't use shared_ptr, and pass arg by reference.
    }

    void start() {
        for (auto d : vec) { /* ...  */ }
    }

private:
    // Idea: std::vector<Base*> vec;
    std::vector<std::shared_ptr<Base>> vec; // For safe memory management
};

Upvotes: 1

Related Questions