2012-05-17 4 views
55

3 개의 파일이 있습니다. 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); 
     } 
} 

내가 정의되지 않은 참조 오류가 다음 명령을 사용하여 이러한 파일을 컴파일하려고

[email protected]:~/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 템플릿 선언 또는 구현에 문제가 있습니까? 왜 M이 링크 오류가 발생합니까?

답변

88

특수하지 않은 템플릿의 구현은이를 사용하는 번역 단위에서 볼 수 있어야합니다.

컴파일러는 코드의 모든 전문 분야에 대한 코드를 생성하기 위해 구현을 볼 수 있어야합니다.

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

많은 사람들이 템플릿 구현을 위해'.tcc' 확장자를 사용합니다 레. –

19

두 가지 방법이 있습니다.

  1. convert2QString을 util.h에 구현하십시오.

  2. 수동으로 util.cpp에 intconvert2QString을 인스턴스화 util.h에 통근 함수로서이 특성화를 정의

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); 
} 
관련 문제