Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to typedef a template class? [duplicate]

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 ?

like image 654
iammilind Avatar asked Aug 02 '11 04:08

iammilind


People also ask

Can you typedef a class?

Similarly, typedef can be used to define a structure, union, or C++ class.

How do you create a object of template class?

Class Template Declarationtemplate <class T> class className { private: T var; ... .. ... public: T functionName(T arg); ... .. ... }; In the above declaration, T is the template argument which is a placeholder for the data type used, and class is a keyword.

What is a class template how it is different from function template?

For normal code, you would use a class template when you want to create a class that is parameterised by a type, and a function template when you want to create a function that can operate on many different types.

Which keyword is used to define a class template?

The class keyword is used to specify a generic type in a template declaration.


1 Answers

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.

like image 90
Travis Gockel Avatar answered Sep 24 '22 08:09

Travis Gockel