未定义的参考模板函数 [英] undefined reference to template function

查看:200
本文介绍了未定义的参考模板函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个文件。 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

util.h

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

util.cpp

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

是不是有什么毛病模板声明或实施?为什么M I得到这些链接错误:

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.

编译器必须能够看到以产生code在您的code所有专业的实施。

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)将头内的实施。

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

这篇关于未定义的参考模板函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆