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++??
Yes, in C++11.
template <typename T>
using DynamicArray = std::vector<T>;
(Not that you should use this exact alias.)
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;
}
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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With