10

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?

2
  • Could you elaborate on why you would want this? Feb 13, 2009 at 8:23
  • 5
    @Eydne, What if he wants to change MyArray to a std::list under the hood without breaking existing code?
    – strager
    Feb 13, 2009 at 21:17

3 Answers 3

14

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.

1
  • Greg, thanks for fixing my syntax. Can you tell that I've been using a lot of Java lately? ;)
    – Thomas
    Feb 13, 2009 at 19:43
10

As of C++11 you can use a templated type alias

template <typename T>
using MyArray = std::vector<T>;

If you want to be more generic you can use a variadic template (which would allow for allocators in the case of vector without having to be specific)

template <typename... Ts>
using MyArray = std::vector<Ts...>;
5

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.

2
  • This can be a bad idea: std::vector does not have a virtual destructor. If you ever need to add a destructor to MyArray, there's a chance it might not be called.
    – Mike
    Jul 13, 2012 at 15:35
  • Another problem is that MyArray<T> and std::vector<T> are different types, and overload resolution will behave differently for the two example May 16, 2017 at 18:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.