Suppose, I'm writing a code that contains many template
functions across many files. The code is supposed to be used with different datatypes. My first attempt was something like as follows (it's just an example, not my actual project):
main.cpp
#include <iostream>
#include "template.h"
int main() {
using T = int;
T val{ f<T>() };
std::cout << val;
return 0;
}
template.h
#ifndef TEMPLATE_H
#define TEMPLATE_H
template <typename T>
T f();
#endif // TEMPLATE_H
template.cpp
#include "template.h"
template <typename T>
T f() {
T val{ static_cast<T>(123) };
return val;
}
Compiling the project gave the following error.
/usr/bin/ld: /tmp/ccEH5mLC.o: in function `main':
main.cpp:(.text+0x9): undefined reference to `int f()'
collect2: error: ld returned 1 exit status
Searching for the root of the problem here and there, I have found that it has something to do with template
. ISO C++
provides 2 solutions:
- Physically moving the definition of the
template
function into the.h
file. - Adding the line
template int f<int>();
(ortemplate int f();
) to the.cpp
file.
The first solution may cause significant code bloat
. Thus, as far as I understand, it's not widely used in real projects (I'm not a programmer, so, may be wrong).
The second one doesn't look flexible, since changing T
type will require changing all template int f<int>();
(or template int f();
) in all .cpp
files. Or, if using multiple T
types (int
and double
, for example) will require adding and/or modifying the exising lines.
So, the question is: What solutions (for compiling multiple files projects with many template
functions) are used in real life?
Will be glad to hear about all solutions. (Maybe C++
macros can be somehow used? Or CMake
features?)