Define a prototype for a template function in a class definition and include the default implementation in the header. In a separate cpp file, create a specialization of the template function. When the function is called that matches the specialization, normally the specialized function is called, unless the g++ optimizations (-O<n> ) are turned on. Then the specialization is out of scope, and the default template implementation is called: compile the attached code as follows: g++ special.cpp smain.cpp then run the result: ./a.out # Specialized! # Template function! Now do the same with optimization: g++ -O3 special.cpp smain.cpp and run again: ./a.out # Specialized! # Template function! With optimization on, the specialization is not called. NOTE: This does NOT occur if the class declaration is in the source modue (.cpp), only when it's included from an external header (.h).
Created attachment 21524 [details] tar.gz of source and temporaries source tarball
This is invalid code IIRC and does not requires a diagnostic.
Also included in the attachment is s2.cpp wich is an duplicate example of the specialization in a single module. This sample when compiled does NOT exhibit the same problem as when the class declaration (and template function) occurs in a header.
specialization is required to be done visible in the translation unit when the use is used IIRC.
(In reply to comment #4) > specialization is required to be done visible in the translation unit when the > use is used IIRC. > Makes sense, however I would assume it would work the same way when optimized (-O3). Is that not correct?
No, it's not. Your testcase violates the ODR and inlining makes that visible.
Thus, invalid.
(In reply to comment #7) > Thus, invalid. > understood. Thanks.