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

标签 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

最佳答案

您声明模板函数 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/

相关文章:

c++ - 即使一切看起来都是 "good", std::mutex::lock 也会抛出吗?

c++ - 重载运算符不能用于为其定义的类

c++ - 多站点执行 : Getting rid of virtual table with inheritance (legacy code)

c++ - g++ 不采用的可变参数推导指南,clang++ 采用 - 谁是正确的?

c++ - 在cuda中用作模板参数

c++ - 为什么不将临时对象传递给另一个线程会导致未定义的行为?

c++ - windows平台下visual studio C++环境下如何使用xgboost?

c++ - Visual Studio C++ 枚举需要很长时间才能编译

php - 使用模板的电子邮件功能。通过 ob_start 和全局变量包含

c++ - InterlockedCompareExchange64 与 std::atomic compare_exchange