C++11 Tidbits: Template Aliases

In terms of ISO C++ Standardization the concept of Template Aliases dates back to 2002 although, at that time, many people used the name "Typedef Templates". In subsequent years Gabriel Dos Reis and Bjarne Stroustrup, in particular, developed the idea into the form which is now part of the C++11 Standard (n2258 is the last free standing paper describing it).

In GCC the implementation is, unfortunately, rather recent. Only the forthcoming GCC 4.7 release series (release candidates are out for testing!) will include it. Maybe the delay is also the fault of library people not pushing for it strongly enough: it's relatively simple to implement and it helps the C++11 library in important areas such as containers and memory.

As it happens the core idea is pretty easy to explain: provide an alias for a family of types. Note that there are no new keywords involved: the using keyword is 'recycled' for the new syntax. For example (directly from n2258):

  #include <vector>

  template<class T> struct Alloc { /* ... */ };
  template<class T>
    using Vec = std::vector<T, Alloc<T>>;

  Vec<int> v;   // same as std::vector<int, Alloc<int>> v;

Here using declares a name Vec for a family of types, which are all the possible std::vector<T, Alloc<T>>, for any T. Then the template alias can be used as any other template, thus by providing between angle brackets an argument for T.

Much more complex examples are possible but there isn't much more to the syntax. It may be interesting to see another simple one which historically motivated the proposals. It is directly inspired by the rebind member of the std::allocator class - which many novice programmers find quite obscure:

  template<typename T>
    class allocator
    {
      //...
 
      template<typename U>
        struct rebind { typedef allocator<U> other; };
    };

   allocator<T>::rebind<U>::other x;  // sample usage

this can now be rewritten:

  template<typename T>
    class allocator
    {
      //...

      template<typename U>
        using rebind = allocator<U>;
    };

   allocator<T>::rebind<U> x;         // sample usage

Indeed, in the C++11 library there are many rebind-style template aliases in the areas of memory allocation, pointer traits, and everywhere: just grep inside the current GCC headers for concrete examples!

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

C++ enthusiasts only, please! ;)

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today