Error in unused template method

struct B { int a; void foo() {a = 5;} }; template <typename T> struct A { A(int i) { B::foo(); } A(double d) {} }; int main() { A<int> a(5.0); } 

gcc 4.7.2 compiles it without errors. clang 3.4svn complains:

 $ clang -Wall -Wextra test.cpp test.cpp:10:16: error: call to non-static member function without an object argument A(int i) { B::foo(); } ~~~^~~ 

Of course, the code is wrong, but which compiler complies with the standard?

It is also strange that clang does not print any notes "in the instance", for example gcc, if you use 5 instead of 5.0:

 $ gcc test.cpp test.cpp: In instantiation of 'A<T>::A(int) [with T = int]': test.cpp:15:12: required from here test.cpp:9:13: error: cannot call member function 'void B::foo()' without object 
+4
source share
1 answer

Your program is incorrect, and both compilers are right, since the standard does not require diagnostics from the corresponding compiler (allowing gcc to ignore it). A template for which there cannot be a valid instance (specializing in standard jargon) is incorrect even if this template is never created.

In your case, the name B::foo() inside A<T>::A(int) is an optional name, so it needs to be resolved during the first phase search, and it can only refer to the class B defined above. Since this is not a static member function, but not static, the code is incorrect regardless of the type T used to instantiate the template A<T> , and the program is poorly formed.

Corresponding quote - from 14.6 [temp.res] / 8:

Knowing which names are type names, you can check the syntax of each template definition. Diagnostics should not be issued to identify a template for which a valid specialization can be created. If a valid specialization cannot be created for the template definition and this template is not created, the template definition is poorly formed, diagnostics are not required.

+5
source

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


All Articles