Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template typedef for std container (without specialization)?

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++??

like image 420
dtech Avatar asked Apr 27 '12 13:04

dtech


3 Answers

Yes, in C++11.

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

(Not that you should use this exact alias.)

like image 92
Cat Plus Plus Avatar answered Nov 10 '22 11:11

Cat Plus Plus


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;
}
like image 22
log0 Avatar answered Nov 10 '22 10:11

log0


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;
};
like image 3
PlasmaHH Avatar answered Nov 10 '22 11:11

PlasmaHH