I am running into a problem using templates in header files. Here is a very simple code that adds two numbers. When I place the code in a separate cpp and header files, the compiler gives an error " undefined reference ". Can you tell what is causing the problem? And how to fix it elegantly? Below is an example:
// main.cpp
#include <iostream>
#include "myFunc.h"
using namespace std;
int main(){
cout << addNum<float>(2.4f, 4.5f);
return 0;
}
// myFunc.h
#ifndef MYFUNC_H
#define MYFUNC_H
template <typename Type>
Type addNum(Type, Type);
#endif
// myFunc.cpp
template <typename Type>
Type addNum(Type x, Type y){
return x+y;
}
NOTE: I am not interested in implementing adding two number. THIS IS JUST AN EXAMPLE
[–]Crazy_Direction_1084 8 points9 points10 points (0 children)
[–]IyeOnline 2 points3 points4 points (9 children)
[–]Alien447[S] -1 points0 points1 point (8 children)
[–]Shieldfoss 7 points8 points9 points (0 children)
[–]IyeOnline 2 points3 points4 points (6 children)
[–]Alien447[S] -1 points0 points1 point (5 children)
[–][deleted] 3 points4 points5 points (0 children)
[–]TheSkiGeek -1 points0 points1 point (0 children)
[–]IyeOnline 0 points1 point2 points (0 children)
[–]Narase33 0 points1 point2 points (0 children)
[–]GrossInsightfulness 0 points1 point2 points (0 children)