views:

140

answers:

2

How would I do to extend a template class, for example vector? The below code does not work. The compiler whines about 'Vector' not being a template.

template <typename T>
class Vector<T> : public std::vector<T>
{
public:
    void DoSomething()
    {
        // ...
    }
};
+13  A: 

Your syntax is wrong; you need to use:

template <typename T>
class Vector : public std::vector<T>

That said, you should not extend the standard library containers via inheritance, if for no other reason then because they do not have virtual destructors and it is therefore inherently unsafe.

If you want to "enhance" std::vector, do so using composition (i.e., with a member variable of std::vector type) or use non-member functions to provide your additional functionality.

James McNellis
+5  A: 

This has nothing to do with extending another class. The problem is your own derived class.

You define a class template like this:

template <typename T>
class Vector
{
...

and not

template <typename T>
class Vector<T>
{
...
jalf
jalfi is right: class Vector<T> is Java syntax, not C++ syntax.
Sagekilla
It's the syntax for a specialization, hence the compiler expects to have seen a base template for `Vector`.
UncleBens