对模板函数的未定义引用

2021-12-09 00:00:00 qt c++ boost undefined-reference

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

I have three files . The contents of main.cpp are

#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);
        }
}

当我尝试使用以下命令编译这些文件时,出现未定义的引用错误

When I try to compile these files with following command I get undefined reference error

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

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

Is there something wrong with the template declaration or implementation ? why M I getting these linking errors :?

推荐答案

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

The implementation of a non-specialized template must be visible to a translation unit that uses it.

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

The compiler must be able to see the implementation in order to generate code for all specializations in your code.

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

This can be achieved in two ways:

1) 将实现移到标题内.

1) Move the implementation inside the header.

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

2) If you want to keep it separate, move it into a different header which you include in your original header:

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);
        }
}

相关文章