Reputation: 3
Hello I am having some troubles with linking header files that contains templates. I have heard that using namespace could resolve this linking issue, but I could not get it to work. Thanks in advance.
//utility.h
#ifndef _UTILITY_H_
#define _UTILITY_H_
#include<iostream>
#include<string>
#include<vector>
using namespace std;
namespace utility
{
template<typename T>
void space_b4(T &value, int &max_num_length);
template<class T>
string doub_to_str(T &d); //Converting double to string.
}
using namespace utility;
template<class 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 << " ";
}
}
#endif
Here is my main cpp file: Data management.cpp
//Data management.cpp
#include <iostream>
#include"utility.h"
using namespace std;
using namespace utility;
int main()
{
double a;
int max;
max = 10;
utility::space_b4(a, max);
}
Here are the error messages:
1>Data management.obj : error LNK2019: unresolved external symbol "void __cdecl utility::space_b4<double>(double &,int &)" (??$space_b4@N@utility@@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
Upvotes: 0
Views: 108
Reputation: 15814
You declare template functions utility::space_b4
and utility::doub_to_str
, but the definitions are in global namespace.
To fix this, move the definitions into the namespace utility { }
block:
namespace utility
{
template<typename T>
void space_b4(T &value, int &max_num_length);
template<class T>
string doub_to_str(T &d); //Converting double to string.
}
namespace utility
{
template<class 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 << " ";
}
}
}
Upvotes: 2