Re: Template Functions

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance

From: Victor Bazarov (v.Abazarov_at_comAcast.net)
Date: 01/20/05


Date: Thu, 20 Jan 2005 13:16:36 -0500

Charles wrote:
> [...] I just can't understand
> why the location of the code should matter. Any help would be greatly
> appreciated, PS. I am using Visual Studio .NET 2002.

Templates need to be fully visible to the compiler when it generates
the code to _instantiate_ them. The instantiation is either implicit
or explicit. When you don't have an explicit instantiation, the
compiler has to resort to implicit instantiation which it performs
when it sees the function (in your case) _used_, i.e. when compiling
the 'main.cpp' module. If the function template is not visible to
the compiler when compiling 'main.cpp', it is unable to instantiate
the template, i.e. create the code for that function. If it can't
create the code, the function doesn't exist (only the template for it
does), it can't find it during linking.

A way to solve it is to instantiate the function _explicitly_. That
is usually a good way to go about instantiating templates if you need
them in a library or something like that. Add to 'test.cpp':

-------- test.cpp
    ...
    template void ConvertFToC<double>(double, double&);
--------

Read more about templates in "C++ Templates" by Vandevoorde and Josuttis.

V



Relevant Pages

  • Re: name binding from one template to another
    ... compiler binds another referred template from one template in the ... The compiler can look up primary template itself in the first phase - ... I am wrong that compiler will do nothing to bind the referred ... compiler won't instantiate vector until it has to instantiate func. ...
    (microsoft.public.vc.language)
  • Re: template compile errors
    ... gcc throws some strange linking errors. ... code for a template doesn't really exist until you instantiate it... ... compiler generates another set of code and data specific to those types. ...
    (comp.lang.cpp)
  • Re: Member function templates in libraries
    ... > libraries. ... the template functions are instantiated in a cpp file ... It's not possible in any compiler that exists today that doesn't implement ... instantiate it at the time of use because I didn't provide the definition. ...
    (comp.lang.cpp)
  • Re: friend of template class
    ... doesn't actually enforce that) declare the template friend function, ... What actually happens here, is that when you instantiate the template class, ... can't give compiler a hint where to look for it's definition for the ...
    (alt.comp.lang.learn.c-cpp)
  • Re: objects? we dont need no stinking objects!
    ... specific language. ... The compiler doesn't know how many objects you will ... instantiate when you compile the code. ... In terms of dynamic arrays under MV ...
    (comp.databases.pick)