Creating a template instance, searching for two-phase names, various behaviors with automatic type inference

After looking at this question When is the instance type of a C ++ template checked? , and I ask myself, I started playing with the code for a long time to learn knowledge. The answer provides a clear and correct explanation. It mentions the search for two-phase names and the fact that the end of a translation unit is also considered an instantiation point for function templates. However, when using the automatic subtraction of the return type, I observed different behavior:

This is similar to the source code. This is correct and works as described in the related post:

class A; class B; template <class T> auto foo() -> T * { A *pa = nullptr; // ignore pa being `nullptr`. return static_cast<T *>(pa); } auto test() { return foo<B>(); } class A {}; class B : public A {}; 

When using automatic return type inference for the foo template, the definitions of A and B should appear before the foo creation point:

Does not work:

 class A; class B; template <class T> auto foo() { // automatic return type deduction A *pa = nullptr; return static_cast<T *>(pa); } auto test() { return foo<B>(); } class A {}; class B : public A {}; 

Gcc error (4.9 and 5.2.1):

error: invalid static_cast from type 'A * to type' B *

Clang gives a similar error

IN:

 class A; class B; template <class T> auto foo() { // automatic return type deduction A *pa = nullptr; return static_cast<T *>(pa); } class A {}; class B : public A {}; auto test() { return foo<B>(); } 

Why is this happening? Why does the rule about the end of the compilation block, considered the instantiation point, no longer make the template instance legal?

+5
source share

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


All Articles