Template specialization in another C ++ file. Which version

I have these files: -

1.h: -

#include <iostream> using namespace std; template <typename A> void f() { cout<<"generic\n"; } 

1.cpp: -

 #include "1.h" template <> void f<int> () { cout<<"for ints only\n"; } 

main.cpp: -

 #include "1.h" int main() { f<int>(); return 0; } 

Now I compile and run them using g ++ as follows: -

 g++ -c 1.cpp -o 1.o g++ main.cpp 1.o ./a.out 

And I get: -

 for ints only 

On the other hand, I compile it using icpc as follows: -

 icpc -c 1.cpp -o 1.o icpc main.cpp 1.o ./a.out 

And I get: -

 generic 

What does the C ++ standard say about this? Is either compiler “correct” and the other “incorrect” or is the standard ambiguous on this issue, and both are “correct”?

+6
source share
1 answer

Your program shows undefined behavior. Specialization must be declared in each translation unit in which it is used, for C ++ 11 §14.7.3 / 6:

If a template, a member template, or a member of a class template is explicitly specialized, then this specialization must be declared before the first use of this specialization, which will cause an implicit instantiation, in each translation unit in which such use is used; no diagnostics required.

+9
source

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


All Articles