With this question I'd like to better understand how C++ templates system works with regards to this question.
As far as I know, template-based classes and functions are usually placed into header files. This is due to the technical issue of managing generic data types, which characterstics are unknown in principle. As soon as they are known, the compiler can generate the executable code which is suited for the required data type.
In the header file something.h
, our class shall be defined as follows:
template <typename T>
class Something
{
public:
void setElement (T &elem) {
element = elem;
}
T getElement () {
return element;
}
private:
T element;
};
Now let's suppose to split source and class definition:
The following class definition will be written in something.h
:
template <typename T>
class Something
{
public:
void setElement (T &elem);
T getElement ();
private:
T element;
};
While the following methods will be written in something.cpp
:
#include "something.h"
template <typename T>
void Something<T>::setElement (T &elem)
{
element = elem;
}
template <typename T>
T Something<T>::getElement ()
{
return element;
}
Unless we declare some specific-type instances inside something.cpp
, if we compile it as object file we won't obtain any text section inside it:
dacav@mithril:<tmp>$ g++ something.cpp -c
dacav@mithril:<tmp>$ objdump -D something.o
something.o: file format elf64-x86-64
Disassembly of section .comment:
0000000000000000 <.comment>:
0: 00 47 43 add %al,0x43(%rdi)
3: 43 3a 20 rex.XB cmp (%r8),%spl
...
...
20: 34 2e xor $0x2e,%al
22: 31 00 xor %eax,(%rax)
dacav@mithril:<tmp>$
As Martin York shows we can force the compiler to generate the code for some specific data types in order to control which types can be used and which cannot. But what if we don't want any restriction?