Reputation: 49289
Is it possible to use typedef on a std container without specializing it?
Code like this works:
typedef std::vector<int> intVector;
But for this code:
template <typename T>
typedef std::vector<T> DynamicArray<T>;
I get an error:
template declaration of 'typedef'
It is possible to do this in C++??
Upvotes: 7
Views: 2487
Reputation: 10917
If your compiler support c++11:
template <typename T>
using DynamicArray = std::vector<T>;
otherwise (c++98 or older) you can use a help structure like the following
template<typename T>
struct DynamicArray
{
typedef std::vector<T> type;
};
and then use it as
DynamicArray<int>::type my_array;
Inheriting from std::vector is a possible solution but be aware that STL containers do not have virtual destructor. i.e.:
template <typename T>
struct DynamicArray: vector<T> { ... };
int main() {
vector<int>* p = new DynamicArray<int>();
delete p; // this is Undefined Behavior
return 0;
}
Upvotes: 6
Reputation: 16046
This syntax is invalid in C++, there is no feature like a "template typedef".
template <typename T>
typedef std::vector<T> DynamicArray<T>;
However, C++11 introduces a template alias syntax that is almost like this:
template <typename T>
using DynamicArray = std::vector<T>;
In C++03 you can use a template metafunction like:
template<class T>
struct DynamicArray
{
typedef std::vector<T> type;
};
Upvotes: 3
Reputation: 129764
Yes, in C++11.
template <typename T>
using DynamicArray = std::vector<T>;
(Not that you should use this exact alias.)
Upvotes: 11
Reputation: 52519
The common solution (if you're not using C++ 11) is to do this:
template<class T>
struct DynamicArray
{
typedef std::vector<T> Type;
};
And use it as DynamicArray<Something>::Type
.
Upvotes: 2