我有一个C++,它使用在单独的.hp/.cpp文件上指定的类。这个类的特殊性在于它有一个以const std::vector
为参数的模板化成员函数,这就是问题的根源。
myclass.hpp
:
class myclass {
//...
public:
myclass();
template <typename _t> int myfunction(const std::vector<_t> *values);
//...
}
myclass.cpp
:
#include "myclass.hpp"
//...
template <typename _t> int myclass::myfunction(const std::vector<_t> *values){
// do stuff
return 0;
}
和我的main.cpp
:
#include "myclass.hpp"
int main(int argc, char const *argv[]){
myclass foo;
std::vector<int> bar(5,100);
foo.myfunction(bar);
return 0;
}
然而,当我试图用g++ main.cpp myclass.cpp -o main -I /usr/include
编译所有这些时,我得到了错误:
undefined reference to `int myclass::myfunction<int>(std::vector<int, std::allocator<int> > const*)'
这很奇怪,因为语法似乎是正确的(并且它通过了g++检查)。问题不在于我如何构建代码或文件设置,因为如果我注释掉模板化的函数,我就可以编译代码。
模板函数必须放在头中,而不是放在源中。这是因为模板基本上是编译器的一条指令,告诉他如何为一组模板参数生成代码。这不是定义本身。所以当实例化特定的专门化时,模板"body"必须是可用的。
简单地说,这个代码:
template <typename _t> int myclass::myfunction(const std::vector<_t> *values){
// do stuff
return 0;
}
应该放在.hpp
文件中,而不是.cpp
文件中。
您可能还想阅读这个SO问题:链接。