using keyword
Contents
Introduction
File: using1.cpp
#include <iostream> #include <vector> #include <memory> using namespace std ; // Alias template for a custom smart pointer template <typename T> using MySmartPtr = std::unique_ptr<T>; int main() { // Traditional typedef typedef std::vector<int> IntVectorOld ; // C++11 using for type alias using IntVectorNew = std::vector<int> ; IntVectorOld v1 ; v1.push_back( 2 ) ; IntVectorNew v2 ; v2.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 std::vectorIntVectorOld ; // C++11 using for type alias using IntVectorNew = std::vector ; However "using" can also alias templates: template using MyVector = vector ; MyVector v3 ; v3.push_back( 2 ) ; We create an object of "MyVector" by supplying the type "int" . The "MySmartPtr" works in a similar manner.