【问题标题】:undefined reference to template function [duplicate]对模板函数的未定义引用[重复]
【发布时间】:2012-05-24 19:48:08
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: c++ qt boost undefined-reference


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 很多人对模板实现文件使用.tcc扩展名。
    • 第一次听到.tcc
    【解决方案2】:

    你有两种方法:

    1. 在 util.h 中实现 convert2QString

    2. 在 util.cpp 中使用 int 手动实例化 convert2QString,并在 util.h 中将此特化定义为 extern 函数

    util.h

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

    util.cpp

     namespace Util {
         template<class T>
         QString convert2QString(T type, int digits)
         {
             using std::string;
    
             string temp = (boost::format("%1") % type).str();
    
             return QString::fromStdString(temp);
         }
    
         template <> QString convert2QString<int>(int type , int digits); 
    }
    

    【讨论】:

      猜你喜欢
      • 2014-04-30
      • 1970-01-01
      • 2015-10-12
      • 2012-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多