Typedef template for std container (no specialization)?

Is it possible to use typedef in a std container without specializing in 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 message:

'typedef' template declaration

Can this be done in C ++ ??

+5
source share
5 answers

Yes, in C ++ 11.

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

(Not that you used this exact alias.)

+9
source

If your compiler supports C ++ 11:

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

otherwise (C ++ 98 or later) you can use a help structure like the following

template<typename T>
struct DynamicArray
{
  typedef std::vector<T> type;
};

and then use it like

DynamicArray<int>::type my_array;

Inheriting from std :: vector is a possible solution, but keep in mind that STL containers do not have a 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;
}
+6

++, , " typedef".

template <typename T>
typedef std::vector<T> DynamicArray<T>;

++ 11 , :

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

++ 03 , :

template<class T>
struct DynamicArray
{
    typedef std::vector<T> type;
};
+3

( ++ 11):

template<class T>
struct DynamicArray
{
    typedef std::vector<T> Type;
};

DynamicArray<Something>::Type.

+2

++ 11 Visual Studio, std::vector, , :

template <typename T>
class DynamicArray : public std::vector<T> {
public:
    DynamicArray& operator<<(const T& value)
    {
        push_back(value);
        return *this;
    }
};

push_back :

DynamicArray<int> array;
array << 1 << 2 << 3 << 4 << 5 << 6;

, - , , , , !

0

All Articles