c++调用在单独的头文件和cpp文件中定义的模板函数

c++ calling a template function defined in separate header and cpp files

本文关键字:文件 定义 函数 cpp 单独 调用 c++      更新时间:2023-10-16

我有一个简单的模板函数,

A.h

#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文件,那么它就可以工作。。。

知道是什么原因造成的吗?

感谢

编译器在编译时需要模板的完整定义。因此,模板函数的定义需要在标头中。(除非您专门化,否则必须在c++文件中或内联)