在头文件中使用模板

时间:2015-04-18 23:25:07

标签: c++ templates c++11

您好我在链接包含模板的头文件时遇到了一些麻烦。我听说使用命名空间可以解决这个链接问题,但我无法让它工作。提前谢谢。

//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

这是我的主要cpp文件: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);
 }

以下是错误消息:

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

1 个答案:

答案 0 :(得分:2)

您声明了模板函数utility::space_b4utility::doub_to_str,但这些定义位于全局命名空间中。

要解决此问题,请将定义移至namespace utility { }块:

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 << " ";
    }
}
}