Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visibility of template specialization of C++ function

Tags:

Suppose I have fileA.h which declares a class classA with template function SomeFunc<T>(). This function is implemented directly in the header file (as is usual for template functions). Now I add a specialized implementation of SomeFunc() (like for SomeFunc<int>()) in fileA.C (ie. not in the header file).

If I now call SomeFunc<int>() from some other code (maybe also from another library), would it call the generic version, or the specialization?

I have this problem right now, where the class and function live in a library which is used by two applications. And one application correctly uses the specialization, while another app uses the generic form (which causes runtime problems later on). Why the difference? Could this be related to linker options etc? This is on Linux, with g++ 4.1.2.

like image 469
oliver Avatar asked Sep 12 '08 15:09

oliver


People also ask

When we specialize a function template it is called?

To do so, we can use a function template specialization (sometimes called a full or explicit function template specialization) to create a specialized version of the print() function for type double.

What is the main advantage of using template functions?

Some of the advantages of using templates are: Templates simplify the creation of documents. Templates can ease our workload and make us feel less stressed, and, at the same time, they increase efficiency. Templates increase the attention of the audience.

What is the main advantage of using template functions in C++?

Advantages. C++ templates enable you to define a family of functions or classes that can operate on different types of information. Use templates in situations that result in duplication of the same code for multiple types.

How function template is defined?

Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type.


1 Answers

It is an error to have a specialization for a template which is not visible at the point of call. Unfortunately, compilers are not required to diagnose this error, and can then do what they like with your code (in standardese it is "ill formed, no diagnostic required").

Technically, you need to define the specialization in the header file, but just about every compiler will handle this as you might expect: this is fixed in C++11 with the new "extern template" facility:

extern template<> SomeFunc<int>(); 

This explicitly declares that the particular specialization is defined elsewhere. Many compilers support this already, some with and some without the extern.

like image 122
Anthony Williams Avatar answered Sep 23 '22 00:09

Anthony Williams