在头文件中使用模板

Using templates in header file

本文关键字:文件      更新时间:2023-10-16

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

//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文件:数据管理.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:Usersliuxi_000DocumentsC++Final project_testFinal ProjectDebugFinal Project.exe : fatal error LNK1120: 1 unresolved externals

声明模板函数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 << " ";
    }
}
}