using keyword
Contents
Introduction
File: using1.cpp
#include <iostream> #include <vector> #include <memory> using namespace std ; // Alias template template <typename T> using MyVector = vector<T>; // Alias template for a custom smart pointer template <typename T> using MySmartPtr = unique_ptr<T>; int main() { // Traditional typedef typedef vector<int> IntVectorOld ; // C++11 using for type alias using IntVectorNew = vector<int> ; IntVectorOld v1 ; v1.push_back( 2 ) ; IntVectorNew v2 ; v2.push_back( 2 ) ; MyVector<int> v3 ; v3.push_back( 2 ) ; // Usage MySmartPtr<int> ptr_to_int( new int(10) ) ; MySmartPtr<double> ptr_to_double( new double(3.14) ) ; return 0; } We had the "typedef" key word pre C++ 11 that lets us alias a type. There is a new keyword "using" that can also alias types. From the above code: typedef vector<int> IntVectorOld ; // C++11 using for type alias using IntVectorNew = vector<int> ; However "using" can also alias templates: template <typename T> using MyVector = vector<T>; MyVector<int> v3 ; v3.push_back( 2 ) ; We create an object of "MyVector" by supplying the type "int" . The "MySmartPtr" works in a similar manner.