c++ - 对模板成员函数的 undefined reference

标签 c++ qt

我正在使用 Qt 5.5.1 并尝试为我的应用程序中的某些属性使用模板类,但在构建时我得到了对该模板类的每种类型的 undefined reference 。

这个构建曾经在 MSVC++ 2015 中工作,但在切换到 Qt 之后我相信我可能没有遵循一些语法约定?

这是我的头文件:

#include <array>
#include <string>
using namespace std;

template <const int SIZE>
class Property
{
public:
    Property(const array<pair<int, string>, SIZE>* properties);
    ~Property();
    string getPropertyValue(int code);
private:
    const array<pair<int, string>, SIZE>* mProperties;
};

这是我的源文件:

#include "Property.h"

template <const int SIZE>
Property<SIZE>::Property(const array<pair<int, string>, SIZE>* properties)
{
    mProperties = properties;
}

template <const int SIZE>
Property<SIZE>::~Property() {}

template <const int SIZE>
string Property<SIZE>::getPropertyValue(int code)
{
    for (int i = 0; i < SIZE; i++) 
    {
        if( code == mProperties[0][i].first )
        {
             return mProperties[0][i].second;
        }
    }

    string("no value found");
}

这是我的实现:

#include <iostream>
#include "Property.h"
using namespace std;

const int arrSize = 1;
const array<pair<int, string>, arrSize> arrValues{
    make_pair(0x02, string("String Value"))
};

int main()
{
    Property<arrSize>* properties = new Property<arrSize>(&arrValues);
    cout << properties->getPropertyValue(2) << endl;
    return 0;
}

这是我的构建输出:

undefined reference to `Property<1>::Property(std::array<std::pair<int, std::string>, 1u> const*)'
undefined reference to `Property<1>::getPropertyValue(int)'

我想要多个属性,编译器提示每个不同大小的 Property<2>::... Property<44>::... 等等...任何帮助将不胜感激。另外,像这样进行代码/值查找的更好方法是什么?

谢谢!

最佳答案

模板只需要在头文件中定义,这就是您得到 undefined reference 的原因。一旦我将源模板代码文件移动到头文件中,我就能够成功运行它。

关于c++ - 对模板成员函数的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33985528/

相关文章:

C++指针声明

c++ - 为什么 C++ 编译器不做更好的常量折叠?

c++ - QListWidget 中的 setSelectionModel 停止发射 itemSelectionChanged 信号

c++ - QScrollArea 获取滚动或总偏移量

c++ - 实现无临时转换运算符

c++ - Visual Studio 2008 中是否有 stoll()/stroll() (字符串到 long long)替代方案

c++ - 使用互斥锁作为信号量?

qt - 如何在 Qt 程序中嵌入二进制可执行文件(将在运行时执行)?

qt - 当用户打开菜单或调整窗口大小时,QMainWindow 停止接收 QEvent::UpdateRequest

c++ - Qt 无法将静态库中的 *​​.h 包含到我的程序中