c++ - 如何定义一个模板类并将其分成多个文件?

标签 c++ templates linker-errors header-files

我写了一个简单的模板类用于测试目的。它编译没有任何错误,但是当我尝试在 main() 中使用它时,它给出了一些链接器错误。


ma​​in.cpp

#include <iostream>
#include "MyNumber.h"

int wmain(int argc, wchar_t * argv[])
{
    MyNumber<float> num;
    num.SetValue(3.14);
    std::cout << "My number is " << num.GetValue() << "." << std::endl;
    
    system("pause");
    return 0;
}



MyNumber.h

#pragma once

template <class T>
class MyNumber
{
    public:
        MyNumber();
        ~MyNumber();
        void SetValue(T val);
        T GetValue();

    private:
        T m_Number;
};



我的号码.cpp

#include "MyNumber.h"

template <class T>
MyNumber<T>::MyNumber()
{
    m_Number = static_cast<T>(0);
}

template <class T>
MyNumber<T>::~MyNumber()
{
}

template <class T>
void MyNumber<T>::SetValue(T val)
{
    m_Number = val;
}

template <class T>
T MyNumber<T>::GetValue()
{
    return m_Number;
}



当我构建此代码时,出现以下链接器错误:

Error 7 Console Demo C:\Development\IDE\Visual Studio 2010\SAVE\Grand Solution\X64\Debug\Console Demo.exe 1 error LNK1120: 4 unresolved externals

Error 3 Console Demo C:\Development\IDE\Visual Studio 2010\SAVE\Grand Solution\Console Demo\main.obj error LNK2019: unresolved external symbol "public: __cdecl MyNumber::~MyNumber(void)" (??1?$MyNumber@M@@QEAA@XZ) referenced in function wmain

Error 6 Console Demo C:\Development\IDE\Visual Studio 2010\SAVE\Grand Solution\Console Demo\main.obj error LNK2019: unresolved external symbol "public: __cdecl MyNumber::MyNumber(void)" (??0?$MyNumber@M@@QEAA@XZ) referenced in function wmain

Error 4 Console Demo C:\Development\IDE\Visual Studio 2010\SAVE\Grand Solution\Console Demo\main.obj error LNK2019: unresolved external symbol "public: float __cdecl MyNumber::GetValue(void)" (?GetValue@?$MyNumber@M@@QEAAMXZ) referenced in function wmain

Error 5 Console Demo C:\Development\IDE\Visual Studio 2010\SAVE\Grand Solution\Console Demo\main.obj error LNK2019: unresolved external symbol "public: void __cdecl MyNumber::SetValue(float)" (?SetValue@?$MyNumber@M@@QEAAXM@Z) referenced in function wmain

但是,如果我将 main() 留空,我不会收到任何链接器错误。

我的模板类有什么问题?
我做错了什么?

最佳答案

您必须为您使用的每个模板参数显式实例化您的模板。

即,在 MyNumber.cpp 文件末尾添加以下行:

template class MyNumber<float>;

这样,链接器将能够找到它需要的所有模板实例化。

另见 Moving Templates Out of Header Files .

关于c++ - 如何定义一个模板类并将其分成多个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4526104/

相关文章:

c++ - std::conditional 编译时分支评估

c++ - 什么是 undefined reference /未解析的外部符号错误,我该如何解决?

c++ - "if constexpr()"与 "if()"之间的区别

c++ - 静态编译共享库

c++ - boost::mpl::integral_c 之类的模板可以注册到 Boost.Typeof 吗?

c++ - 有两个不同版本的箭头运算符?

ios - 链接器错误 undefined symbol

c++ - LNK2019 构建 ZeroMQ Hello World 示例时出错。 VS2012 遥控

c++ - 为什么 uint64_t 类型的 -INT_MIN 不是 2147483648

c++ - 使用指针数组中对象的函数