Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 171 ยท Variables and Types

Type Aliases: using and typedef

Learn C++ type aliases with using and the legacy typedef, alias templates, member type aliases like value_type, and why an alias is not a new type.

Some C++ types are long: std::map<std::string, std::vector<std::pair<int, double>>> is a perfectly reasonable type to need, and a miserable one to type five times. Other types are short but say nothing about their meaning: a double could be meters, seconds, dollars or degrees. A type alias gives an existing type a new name, so you can write ScoreTable or Meters instead.

Modern C++ creates aliases with using. Older code uses typedef, which does the same thing with a harder-to-read syntax. In this lesson you'll learn both, see the alias templates that only using can do, meet the aliases the standard library uses everywhere, and learn the most important limitation: an alias is just another name, not a new type.

Creating an alias with using

The syntax reads like an assignment: the new name on the left, the existing type on the right.

C++
using Name = ExistingType;

After that line, Name and ExistingType are interchangeable everywhere. Here is a typical use:

C++ Naming a long type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Notice what the aliases bought you:

  • Readability. average(const Scores& scores) says what the function takes in the language of the problem.
  • One place to change. If scores later need to be double, you change one line (using Scores = std::vector<double>;) instead of hunting through every signature.
  • Shorter code without hiding anything important: the definition is one jump away in any editor.

Aliases follow normal scope rules. One declared inside a function, class or namespace is only visible there, which is a good way to keep a helper name local.

The legacy syntax: typedef

Before C++11, the only way to make an alias was typedef. It works like a variable declaration with the keyword in front, so the new name sits where a variable name would go:

C++
typedef std::vector<int> Scores;                    // same as: using Scores = std::vector<int>;
typedef unsigned long long Id;                      // same as: using Id = unsigned long long;
typedef std::map<std::string, Scores> Gradebook;    // same as: using Gradebook = ...;

For simple types the difference is cosmetic. It gets worse with function pointers and arrays, where the new name ends up buried in the middle:

C++
typedef double (*Operation)(double, double);   // the name "Operation" is in the middle
using Operation = double (*)(double, double);  // the name comes first

typedef int Row[3];                            // "Row" is an array of 3 ints
using Row = int[3];

Both forms of each line mean exactly the same thing, and you can mix them freely. typedef is not deprecated, and you'll read it constantly in C libraries, older C++ code and some platform headers. In new code, prefer using: it reads left to right, and it supports templates, which typedef can't.

C++ Function pointer aliases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Function pointers get a full lesson in Function Pointers and std::function; the point here is how much clearer the using version is to read.

Alias templates (a preview)

using can be combined with template to create an alias template: a family of aliases with a placeholder type. This is something typedef simply can't express:

C++
template <typename T>
using Grid = std::vector<std::vector<T>>;

Grid<int> heights;          // std::vector<std::vector<int>>
Grid<char> maze;            // std::vector<std::vector<char>>

You'll learn templates properly in Function Templates and Class Templates. For now, read template <typename T> as "for any type T":

C++ An alias template

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The standard library uses alias templates itself. For instance, std::remove_reference_t<T> is an alias template for typename std::remove_reference<T>::type (see Type Traits), and std::pmr::vector<T> is an alias for a vector with a special allocator.

Aliases you already use

Many standard library names you meet are aliases, not separate types:

Alias Is actually Where
std::string std::basic_string<char> <string>
std::string_view std::basic_string_view<char> <string_view>
std::size_t an unsigned integer type (unsigned long here) <cstddef>
std::int32_t, std::uint64_t, โ€ฆ fundamental integer types <cstdint>
std::chrono::seconds std::chrono::duration of a signed integer type (long here) <chrono>

Containers also define member type aliases that describe themselves. Every standard container has value_type (the element type), size_type (usually std::size_t), iterator, reference and a few more. Generic code relies on them to work with any container, and you can define the same aliases in your own classes:

C++ Member type aliases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Outside the class you name a member alias with the scope operator: Playlist::Track. You'll write classes like this in Classes and Objects.

An alias is not a new type

This is the limit that trips people up. An alias adds a name, never a type. The compiler treats Meters and double as identical, so it can't stop you from mixing values that only look alike:

C++ Aliases do not protect you

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The swapped call is a real-world bug class: NASA lost the Mars Climate Orbiter in 1999 to a mix-up between pound-force seconds and newton seconds in software. If you want the compiler to catch these mistakes, you need a distinct type, often called a strong type. The simplest version is a small struct:

C++
struct Meters  { double value; };
struct Seconds { double value; };

double speed(Meters distance, Seconds time) {
    return distance.value / time.value;
}

speed(Meters{400.0}, Seconds{50.0});   // fine
speed(Seconds{50.0}, Meters{400.0});   // error: could not convert ... from 'Seconds' to 'Meters'

Now each unit is its own type and swapped arguments don't compile. The standard library does this properly for time: std::chrono::seconds and std::chrono::milliseconds are distinct types that convert correctly and refuse lossy conversions (see chrono). Enumerations work the same way for named integer values: enum class creates a real new type.

So use aliases for readability and maintenance, and use distinct types (structs, classes, enum class) when you need type safety.

Good habits

  • Prefer using over typedef in new code; read both.
  • Name aliases for meaning, not structure. using Inventory = std::map<std::string, int>; is useful; using MapStringInt = std::map<std::string, int>; adds nothing.
  • Don't alias simple types just to rename them. using Integer = int; makes code harder to read. Aliases for int are worthwhile only when they carry intent (using PlayerId = int;) or an exact width (std::int32_t).
  • Keep aliases close to where they're used: inside a class or namespace, or at the top of the .cpp file. Put them in a header only when several files share them.
  • Don't hide pointers behind aliases like using NodePtr = Node*; in public interfaces. Readers lose track of what is a pointer, and const NodePtr means a const pointer, not a pointer to const. Smart pointers (std::unique_ptr<Node>) are usually the better answer anyway.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which line is equivalent to typedef std::vector<std::string> Names;?

    With using, the new name comes first, then =, then the existing type.
  2. 2. using Celsius = double; using Fahrenheit = double; What happens if you pass a Fahrenheit value to a function that takes Celsius?

    An alias is only another name for the same type. To have the compiler reject the mix-up, make Celsius and Fahrenheit distinct types, for example small structs.
  3. 3. What can using do that typedef cannot?

    Both can alias function pointers, member types and built-in types. Only using can be templated.
  4. 4. What is std::vector<double>::value_type?

    Every standard container defines value_type as its element type. For std::vector<double> that is double.

Summary

  • A type alias gives an existing type another name: using Name = Type;. The two names are fully interchangeable.
  • typedef Type Name; is the older syntax with the same meaning; it gets hard to read for function pointers and arrays. Prefer using.
  • Alias templates (template <typename T> using Grid = std::vector<std::vector<T>>;) are only possible with using.
  • The standard library is full of aliases: std::string, std::size_t, std::int32_t, and member aliases like value_type and size_type.
  • An alias is not a new type and gives no type safety. Use structs, classes or enum class when mixing up values must be a compile error.
  • Name aliases for meaning, keep them scoped, and don't hide pointers behind them.

Next: Math Functions, where you'll put these types to work with <cmath>, <numeric> and integer division rules.