Reputation: 453
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?
Upvotes: 10
Views: 4180
Reputation: 36802
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...>;
Upvotes: 11
Reputation: 554
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.
Upvotes: 5
Reputation: 181745
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.
Upvotes: 14