gpt4 book ai didi

c++ - 在头文件中使用模板

转载 作者:行者123 更新时间:2023-11-28 02:28:28 25 4
gpt4 key购买 nike

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

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

最佳答案

您声明模板函数 utility::space_b4utility::doub_to_str,但定义在全局命名空间中。

要解决此问题,请将定义移至 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 << " ";
}
}
}

关于c++ - 在头文件中使用模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29724042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com