tags:

views:

325

answers:

2

Instead of using

std::vector<Object> ObjectArray;

I would like it to be

MyArray<Object> ObjectArray;

with all the std::vector methods preserved. (like push_back(), reserve(), ...etc)

However, using

typedef std::vector MyArray;

won't work. Should I use template instead? How?

Thanks in advance.

+8  A: 

What you would really want is a templated typedef. Unfortunately those are not supported in the current version of C++, but they will be added in C++0x.

For now, here's a possible workaround:

template<class T> struct My {
    typedef std::vector<T> Array;
};

My<Object>::Array ObjectArray

Whether or not that is better than simply using std::vector directly, I'll leave to you to decide.

Thomas
Greg, thanks for fixing my syntax. Can you tell that I've been using a lot of Java lately? ;)
Thomas
Clever use of metaprogramming.
spoulson
+2  A: 

Another way:

#include <vector>

template <typename T>
struct MyArray
    :std::vector<T>
{
};

void func()
{
    MyArray<int> my;

    my.push_back(5);

    MyArray<int>::iterator i;
}

Compiles for me, but you may find that some things available in vector<> need to be "pulled up" into MyArray.

keraba