dawsonc623
dawsonc623

Reputation: 2275

C++ Using a template class pointer as a template parameter without giving it a parameter

The title is a little confusing, so hopefully I can clear that up.

I have a simple class that uses a template:

template <class T>
class Value
{
};

And another class that extends unordered_set:

template<class T>
class Collection : public std::unordered_set<T>
{
};

These classes both have some other code, but I don't think any of it is relevant to my question.

In a particular implementation of the Collection class, I want it to be able to take pointers to any Value, regardless of the template parameter that was used when creating it. In other words, I want to be able to have something semantically similar like this:

class ValueCollection : public Collection<Value*>
{
};

ValueCollection *vc = new ValueCollection();
vc.insert(new Value<std::string>("hello"));
vc.insert(new Value<int>(5));

Of course, that doesn't work. How I would obtain similar functionality?

Upvotes: 1

Views: 114

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153800

Just give you Value class template a common base class, making sure that it has a virtual destructor and using this to add your instantiated values:

struct ValueBase {
    virtual ~ValueBase() {}
};
template <typename T>
struct Value
    : ValueBase {
};

BTW, you are generally better off not inheriting the STL containers: They are not designed for inheritance you are most likely to cause subtle problems than benefitting from the little amount of saved work.

Upvotes: 2

Related Questions