samedi 18 avril 2015

How to use header files for templates correctly? [duplicate]


This question already has an answer here:




Hello I am having troubles of linking header files that contains templates. I am very new to templates, so I can't seem to see the mistakes. Thanks in advance. Here is my header file utility.h



//utility.h
#ifndef _UTILITY_H_
#define _UTILITY_H_
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int checkvali(double &input);
template<typename T>
string doub_to_str(T &d); //Converting double to string.
template<typename T>
void space_b4(T &value, int &max_num_length);
#endif


Here is the cpp file, utility.cpp



//utility.cpp
#include"utility.h"
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int checkvali(double &input)
{
int compr;
compr = static_cast<int>(input);
while (input !=compr|| input< 0||cin.fail()||cin.peek()!='\n'||input ==0)
{
cout<<"Please enter a positive non-zero integer"<<endl<<endl;
cin.clear(); cin.ignore(255,'\n'); cin>> input; compr = static_cast<int>(input);
}
return compr;
}
template<typename T>
string doub_to_str(T &d) //Converting double to string.
{
stringstream ss;
ss << d;
return ss.str();
}
template<typename T>
void space_b4(T &value, int &max_num_length) //This function adds space before an element if the number of digits of this element is less than the maximum number.
{
int d = max_num_length - doub_to_str(value).length();
for (int a = 0; a < d / 2; a++)
{
cout << " ";
}
}


Here is my main cpp file: Data management.cpp



//Data management.cpp
#include"utility.h"
#include <iostream>
using namespace std;
int main()
{
double a; int b;
cin >> a;
b = checkvali(a);
cout<<b;
string c; double d;
d = 100.1;
c = doub_to_str(d);
cout<<d;
int max;
max = 10;
space_b4(d, max);
}


Here are the error messages:



>Data management.obj : error LNK2019: unresolved external symbol "class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl doub_to_str<double>(double &)" (??$doub_to_str@N@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@AAN@Z) referenced in function _main
1>Data management.obj : error LNK2019: unresolved external symbol "void __cdecl space_b4<double>(double &,int &)" (??$space_b4@N@@YAXAANAAH@Z) referenced in function _main
1>C:\Users\liuxi_000\Documents\C++\Final project_test\Final Project\Debug\Final Project.exe : fatal error LNK1120: 1 unresolved externals

Aucun commentaire:

Enregistrer un commentaire