C++11C++14C++17Learn C++Templates

Stages of C++ Templates Compilation On Windows

In order to compile C++ templates the compilers like Embarcadero RAD Studio C++ compilers are required to perform two stages: definition stage and instantiation stage.

The template definition stage

On this stage the following checks are performed:

  • static assertions and availability of names declarations (such as names of classes and functions) independent on template parameters are checked, even if they are belongs to discarded branch of if constexpr statement (on details about compile-time if, please see If Statements in Modern C++);
  • syntax correctness is checked, including for unqualified names which are depends on template parameters.

The complete check of unqualified names is postponed until the template instantiation stage when the template arguments are known.

Please note, since the compilers like Embarcadero RAD Studio C++ performs many checks on this stage a programmer is often see general problems even before the template instantiation stage!

Example of errors even when the branch is discarded at compile-time:

Example of syntax error upon checking of unqualified names which are depends on template parameters:

Another example of syntax error upon checking the construct before period that depends on a template parameter:

The template instantiation stage

The first point where the template is used for a first time for particular template arguments is called the point of instantiation. At this point the template arguments are known hence the compilers are able to generate specializations of templates for concrete arguments. During the generation of a specialization:

  • the lookup is performed for qualified names which depends on template arguments (which are known at this stage);
  • argument-dependent lookup (also known as Andrew Koenig lookup) is performed for unqualified names in order to complete the check initiated on the template definition stage.

Please note, that functions and classes generated from templates are subject to the same rules as for regular functions and classes.

Example of errors during the template instantiation stage:

Oh hi there 👋
It’s nice to meet you.

Sign up to receive awesome C++ content in your inbox, every day.

We don’t spam! Read our privacy policy for more info.

Related posts
C++C++11C++14C++17C++20Introduction to C++Learn C++

Learn Copy Constructors in C++ Classes

C++C++11C++14C++17Introduction to C++Learn C++Syntax

Learn How To Use Types Of Destructors In C++?

C++C++11C++14Learn C++Syntax

How To Convert u32string To A wstring In C++

C++C++11C++14C++17C++20Introduction to C++Learn C++

How To Learn The Move Constructors In Modern C++?

Worth reading...
If Statements In Modern C++