When is a C ++ template instance type checked?

When compiling C ++, gcc and clang seem to delay the type checking of template instances until all program declarations have been processed. Is it guaranteed in the language?

To develop, I can keep the type incomplete at the point where the template was defined, or create an instance of the template if I populate the type somewhere later in the program:

class A; class B; extern A* pa; // 1. template definition template<typename T> T* f() { return static_cast<T*>(pa); } // 2. template instantiation B* test() { return f<B>(); } // 3. completing types class A { }; class B : public A { }; 

Note that the definitions of A and B are required to enter the type of template instance validation (to make static_cast valid). If you leave step 3, step 2 will no longer compile.

In organizing my headers, can I rely on this order to be accepted by any standard C ++ compiler?

+5
source share
1 answer

This rule is called "biphasic name lookup."

Names that do not depend on the template parameters are checked and checked upon determination, and dependent names are checked at the time of instantiation.

In your example, there is one important detail: the end of the translation unit is also considered the instantiation point for function templates:

C ++ 14 N4140 14.6.4.1 [temp.point] P8:

A specialization of a function template, a template of a member function, or a member function or a static data element of a class template can have several instantiation points inside a translation unit and, in addition to the instantiation points described above, for any such specialization that has an instantiation point inside a translation unit, end translation units are also considered a point of specification.

Thus, although the type is not incomplete at point "2", where an explicit instantiation occurs, it ends at the end of the file, which makes the creation of the template legal.

Note : Microsoft compiler does not fully implement this rule, violating the standard. In the Microsoft compiler, the entire search takes place at the time the instance is created (so the example should work, but I do not have access to the MSVC check). Other major compilers implement this rule correctly.

+5
source

Source: https://habr.com/ru/post/1237854/


All Articles