I’m trying to call a function template defined inside a class from within another class, but I’m stuck.
I get error:
1>class1.obj : error LNK2019: riferimento al simbolo esterno "public: void __thiscall class2::output<double,long>(double,long,float)" (??$output@NJ@class2@@QAEXNJM@Z) non risolto nella funzione "public: void __thiscall class1::x(class class2 &)" (?x@class1@@QAEXAAVclass2@@@Z)
1>class1.obj : error LNK2019: riferimento al simbolo esterno "public: void __thiscall class2::output<float,int>(float,int,float)" (??$output@MH@class2@@QAEXMHM@Z) non risolto nella funzione "public: void __thiscall class1::y(class class2 &)" (?y@class1@@QAEXAAVclass2@@@Z)
1>C:\xxx.exe : fatal error LNK1120: 2 esterni non risolti
If I uncomment lines with duplicate functions (the ones without templates) it is ok. Can you help fix it?
File: “class1.h”
#ifndef CLASS1
#define CLASS1
#include "class2.h"
class class1{
public:
void x(class2& c );
void y(class2& c );
};
#endif
File: “class1.cpp”
#include "class1.h"
void class1::x( class2& c )
{
double img;
long integ;
float y;
c.output(img, integ, y);
}
void class1::y(class2& c )
{
float img;
int integ;
float y;
c.output(img, integ, y);
}
File: “class2.h”
#ifndef CLASS2
#define CLASS2
class class2{
void output2(double img, long integ, float y);
void output2(float img, int integ, float y);
public:
template <typename T1, typename T2>
void output(T1 img, T2 integ, float y);
//void output(double img, long integ, float y);
//void output(float img, int integ, float y);
};
#endif
File: “class2.cpp”
#include "class2.h"
template <typename T1, typename T2>
void class2::output(T1 img, T2 integ, float y)
{output2(img, integ, y);}
//void class2::output(double img, long integ, float y)
//{output2(img, integ, y);}
//void class2::output(float img, int integ, float y)
//{ output2(img, integ, y);}
void class2::output2(double img, long integ, float y){/*...*/}
void class2::output2(float img, int integ, float y){/*...*/}
EDIT
I’m talking about function templates and not class templates. I’ve seen the question I would be duplicating before, but it is not what I’m looking for. I have two functions inside a class that are identical except for their parameters type.
I only wanted a simple trick to avoid writing and maintaining identical code for two functions inside the same class. Anyway I’ve found a solution, adding these two lines at the bottom of class2.cpp:
template void class2::output<double, long>(double img, long integ, float y);
template void class2::output<float, int>(float img, int integ, float y);