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: