Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how template instantiation doesn't lead to linking error

Tags:

I know that the following code will result in a linking error:

//first.cpp
void test(){
    //random code
}

//second.cpp
void test(){
    //random code
}

so lets say that we have this function template:

template<typename T>
T test(){
    //random code
}

and are doing this:

//first.cpp
...
test<void>();

//second.cpp
...
test<void>();

so the way I understand how compiler works is that it only cares for each file individually so it only cares that test<void>() must have a definition therefore it will create one. same thing goes for the second.cpp then why don't we get an linker error at later stage when there are two definitions for test<void>.(I think this should be same as the first example where those two void test() functions in separate files lead to a linking error)

if this is a duplicate I'm sorry I literally didn't know how to search for this.

like image 959
ClassY Avatar asked Jul 04 '21 19:07

ClassY


People also ask

What happens when a class template is instantiated?

Template instantiation involves generating a concrete class or function (instance) for a particular combination of template arguments. For example, the compiler generates a class for Array<int> and a different class for Array<double>.

Can using templates lead to errors in the program?

Yes. Template compilation errors are seriously verbose. There's a lot of information there that's not needed. However, most of them do start with the line number of where the template was used.

What is created when the template is instantiated?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation to handle a specific set of template arguments is called a specialization.

What causes a C++ template function to be instantiated?

When a function template is first called for each type, the compiler creates an instantiation. Each instantiation is a version of the templated function specialized for the type. This instantiation will be called every time the function is used for the type.


1 Answers

The linker doesn't complain because the standard says so:

[basic.def.odr]/13

There can be more than one definition of a
...
— inline function or variable ...

— templated entity ...

In this regard, the linker handles them as if they were inline.

Note that they're not actually inline (for the purposes of optimizations). You can mark them as inline yourself, hinting the compiler that they should be inlined.

like image 150
HolyBlackCat Avatar answered Oct 11 '22 20:10

HolyBlackCat