c++调用在单独的头文件和cpp文件中定义的模板函数
c++ calling a template function defined in separate header and cpp files
我有一个简单的模板函数,
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++文件中或内联)
相关文章:
- C++无法定义虚拟函数 OUTER 类和头文件
- QML:修改在不同QML文件(而非main.QML)中定义的子对象的属性
- 尝试调用 .h 文件中定义的变量时出现变量未定义错误
- 在头文件和 cpp 文件中使用一次 #pragma 时出现结构重定义错误
- C++编程从外部文本文件定义数组大小
- MAKE:找不到包含的用户定义的头文件?
- 定义C++新的环境变量并在 bat 文件中使用它
- 在头文件中定义变量不会出错
- 即使我没有包含多个文件,C++中的多个定义错误
- 如何检查函数是否在LLVM Instrumentation pass的ModulePass的系统头文件中定义?
- 查找定义我的 C/C++ 函数/宏的文件比'grep'更简单的方法
- 将文件复制到自定义位置,存在字符串转换问题
- 如何正确定义C++类析构函数并将其链接到主文件?
- C2011: 'Card':"类"类型重新定义(尽管使用了包含保护并且没有在文件中重新定义.cpp类)
- 从头文件定义嵌套类
- 使用标头文件定义MT19937和normal_distribution
- 为特定文件定义
- 从.h和.cpp文件定义纯虚拟函数会产生链接器错误吗
- C 编程从外部输入文件定义数组大小
- 编译头文件定义了一个模板类,该类还包括其他头文件