liveBook · Manning

Type alias

As explained in Learn C++ by Example

A type alias is a declaration that gives an existing type an alternative name.

A type alias gives an existing type another name. In C++, using provides a more general alternative to typedef, making lengthy types easier to read and reuse. section 4.2.2

Naming a custom duration

A century can be represented with a named chrono duration: using centuries = std::chrono::duration<long long, std::ratio_multiply<std::chrono::years::period, std::hecto>>;. Afterward, centuries{2} can be converted to seconds or hours directly, while conversion to days requires duration_cast because the result may contain a fractional day. section 4.2.2

Listing 4.5 Defining a duration
void defining_a_duration()
{
    using namespace std::chrono;
    using centuries = duration<long long, 
        std::ratio_multiply<years::period, std::hecto>>;        #1
    centuries two_hundred_years = centuries(2);                 #1
    seconds sec = two_hundred_years;                            #2
    hours hrs = two_hundred_years;                              #2
    days day_count = duration_cast<days>(two_hundred_years);    #3
    std::cout << "Two centuries is approximately " << day_count << '\n'; 
}

See the complete custom-duration example, including the alias, duration construction, implicit conversions, and explicit conversion to days. section 4.2.2

How Learn C++ by Example covers it

How deep it goes
Defines the using form through a century-duration example and defers broader details about using to later coverage.
Examples
Uses a centuries alias to represent two hundred years and convert that duration into seconds, hours, and days.
What you can do after
Build it from scratch by naming a parameterized chrono duration with using and applying the alias in conversions.
How it connects
Connects type aliases with std::chrono durations, std::ratio, std::ratio_multiply, and duration_cast.

Also explained in

Compare how 6 books explain type alias →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.