2013-07-24 40 views
-2

我有一个简单模板函数定义的模板函数,C++调用单独的头和cpp文件

#include <iostream> 
#include <vector> 

using namespace std; 

template<class T> 
pair<T, T> GetMatchedBin(T, vector<pair<T, T> >); 

A.cpp

#include "A.h" 

template<class T> 
pair<T, T> GetMatchedBin(T val, vector<pair<T, T> > &bins) 
{ 
    for(unsigned int i=0; i<bins.size(); i++){ 
     if(val >= bins[i].first && val < bins[i].second) 
      return bins[i]; 
    } 
    return pair<T, T>(); 
} 

我通过打电话,

main.cpp

#include <iostream> 
#include <vector> 
#include "A.h" 

using namespace std; 

int main() 
{ 
    vector<pair<int, int> > bins; 
    bins.push_back(pair<int, int>(0, 1)); 
    bins.push_back(pair<int, int>(1, 2)); 
    bins.push_back(pair<int, int>(2, 3)); 
    bins.push_back(pair<int, int>(3, 4)); 

    pair<int, int> matched_bin = GetMatchedBin(3, bins); 

    cout << matched_bin.first << ", " << matched_bin.second << endl; 

    return 0; 
} 

然而,当我尝试编译此我得到的错误,

make 
g++ -o temp temp.cpp A.o 
/tmp/dvoong/ccoSJ4eF.o: In function `main': 
temp.cpp:(.text+0x12a): undefined reference to `std::pair<int, int> GetMatchedBin<int>(int, std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > >)' 
collect2: ld returned 1 exit status 
make: *** [temp] Error 1 

奇怪的是,如果我做的这一切都在一个文件中,而不是分成头和.cpp文件,然后它工作.. 。

任何想法是什么造成这种情况?

感谢

+0

见http://stackoverflow.com/q/495021/951890 –

回答

2

编译器需要在编译时模板的完整定义。因此,模板函数的定义需要在标题中。 (除非你专门,是要在一个C++文件或内联)

+0

谢谢,你的回答只是让我想起了我以前已经有过这个问题,一旦 – scruffyDog