The following code in a single .cpp file works fine
#include <iostream>
template<typename T>
void print(int a) {
std::cout << a << std::endl;
}
int main() {
print<int>(5);
}
But if I separate the code into the files main.cpp, print.h and print.cpp respectively like this
#include "print.h"
int main() {
print<int>(5);
}
template<typename T>
void print(int a);
#include <iostream>
template<typename T>
void print(int a) {
std::cout << a << std::endl;
}
then gcc gives me the linker error "undefined reference to `void print<int>(int)'". Why does this happen? What is going wrong when declaring a template function? Is there some other way to do what I want?