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

标签 c++ qt boost undefined-reference

我有三个文件。 main.cpp的内容是

#include<iostream>
#include<QString>

#include "util.h"

int main()
{
    using Util::convert2QString;

    using namespace std;
    int n =22;
    QString tmp = convert2QString<int>(n);

    return 0;
}

util.h

namespace Util
{
    template<class T>
    QString convert2QString(T type , int digits=0);
}

util.cpp

namespace Util
{
    template<class T>
        QString convert2QString(T type, int digits=0)
        {
            using std::string;

            string temp = (boost::format("%1%") % type).str();

            return QString::fromStdString(temp);
        }
}

当我尝试使用以下命令编译这些文件时,出现 undefined reference 错误

vickey@tb:~/work/trash/template$ g++ main.cpp  util.cpp -lQtGui -lQtCore  -I. -I/usr/local/Trolltech/Qt-4.8.0/include/QtCore -I/usr/local/Trolltech/Qt-4.8.0/include/QtGui -I/usr/local/Trolltech/Qt-4.8.0/include
/tmp/cca9oU6Q.o: In function `main':
main.cpp:(.text+0x22): undefined reference to `QString Util::convert2QString<int>(int, int)'
collect2: ld returned 1 exit status

模板声明或实现有问题吗?为什么我会收到这些链接错误:?

最佳答案

非专用模板的实现必须对使用它的翻译单元可见。

编译器必须能够看到实现,以便为代码中的所有特化生成代码。

这可以通过两种方式实现:

1) 将实现移动到标题中。

2) 如果您想将其分开,请将其移动到您包含在原始标题中的不同标题中:

util.h

namespace Util
{
    template<class T>
    QString convert2QString(T type , int digits=0);
}
#include "util_impl.h"

util_impl.h

namespace Util
{
    template<class T>
        QString convert2QString(T type, int digits=0)
        {
            using std::string;

            string temp = (boost::format("%1") % type).str();

            return QString::fromStdString(temp);
        }
}

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

相关文章:

c++ - 为 'gdt_flush' 指定的存储类

c++ - QSqlQuery 与索引一起使用

python - 如何在 Windows 7 上安装 Boost.Python 以安装 python 包?

c++ - 如何使用 QScopedPointer<QApplication>

c++ - 如何为QtCreator创建自定义主题

c++ - 开发-C++/TDM-GCC : Linkage Problems with Boost Libaries Downloaded from boost. 组织

c++ - 时区之间的时间转换

c++ 链接器,如何链接 iostream 文件?

c++ - 是否有 dynamic_cast 的合适替代品

c++ - 为什么用execute::par对 vector 进行排序要比正常排序(gcc 10.1.0)花费更长的时间?