How to typedef a template class?

C++TemplatesC++11Typedef

C++ Problem Overview


How should I typedef a template class ? Something like:

typedef std::vector myVector;  // <--- compiler error

I know of 2 ways:

(1) #define myVector std::vector // not so good
(2) template<typename T>
    struct myVector { typedef std::vector<T> type; }; // verbose

Do we have anything better in C++0x ?

C++ Solutions


Solution 1 - C++

Yes. It is called an "alias template," and it's a new feature in C++11.

template<typename T>
using MyVector = std::vector<T, MyCustomAllocator<T>>;

Usage would then be exactly as you expect:

MyVector<int> x; // same as: std::vector<int, MyCustomAllocator<int>>

GCC has supported it since 4.7, Clang has it since 3.0, and MSVC has it in 2013 SP4.

Solution 2 - C++

In C++03 you can inherit from a class (publically or privately) to do so.

template <typename T>
class MyVector : public std::vector<T, MyCustomAllocator<T> > {};

You need to do a bit more work (Specifically, copy constructors, assignment operators) but it's quite doable.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioniammilindView Question on Stackoverflow
Solution 1 - C++Travis GockelView Answer on Stackoverflow
Solution 2 - C++dascandyView Answer on Stackoverflow