c++templates

How does the compiler handle generic types when compiling them?


I was looking into why the declaration and definition of a template member function should not be created separately. and i found a very good answer.

Templates and separate compilation

and Reading this article made me curious about how to handle <T> when compiling a .cpp file with definitions of class template member functions.

If the compiler compiles this SimpleVector.cpp file, what will it do with <T>?

--- SimpleVector.cpp ---

#include "SimpleVector.h"
#include <algorithm>

template<typename T>
void SimpleVector<T>::sortData() {
    sort(data, data + currentSize);
}

template<typename T>
int SimpleVector<T>::size() { return currentSize; }

template<typename T>
int SimpleVector<T>::capacity() { return currentCapacity; }

First of all, it seems like the compiler will ignore all functions with <T>. Is this correct? If anyone knows how it works, I would appreciate some help. Or please tell me something that might help me understand this. thank you


Thanks for all the comments

Why can templates only be implemented in the header file?

I saw a response to this post and I've excerpted it below.

Meaning typename T get's replaced during the compilation step not the linking step so if I try to compile a template without T being replaced as a concrete value type that is completely meaningless to the compiler and as a result object code can't be created because it doesn't know what T is.

Here, saying the compiler doesn't create object code because it doesn't know what T is mean Does this mean the compiler ignores functions related to T

For example, SimpleVector::sortData() or SimpleVector::size() in SimpleVector.cpp

(and I'm sorry for my poor English skills)


Solution

  • Templates are a compile-time feature in C++, and the compiler only generates code for a template when it encounters a specific instantiation of that template.

    When the compiler processes the SimpleVector code, it sees the definitions of template member functions such as sortData, size, and capacity as templates. However, the compiler does not generate any actual code for these template functions at this stage because there are no concrete types (<T>) specified. Templates are only blueprints until instantiated.

    Since there are no explicit instantiations of SimpleVector<T> in SimpleVector code ( no SimpleVector <int> or SimpleVector <double>), the compiler effectively skips generating code for these functions.

    The compiler generates the actual code for a template function or class only when it knows the type T.