有人可以向我解释为什么以下内容无法编译吗?希望我错过了明显的事情......
函数.hpp:
template<typename T> string vector_tostr(std::vector<T> v);
函数.cpp:
template<typename T> string vector_tostr(std::vector<T> v){
std::stringstream ss;
std::string thestring = "";
if(v.size() > 0){
ss << "[";
for(size_t i = 0; i < v.size(); i++){
if(i != 0)
ss << " ";
ss << v[i];
}
ss << "]";
thestring = ss.str();
}
return thestring;
}
main.cpp
#include "functions.hpp"
int main(int argc, char *argv[]){
vector<int> thevector;
thevector.push_back(1);
thevector.push_back(2);
string result = vector_tostr(thevector);
//I have also tried vector_tostr<int>(thevector)
}
我收到的神秘错误如下:
体系结构 x86_64 的未定义符号:“std::basic_string, std::allocator >
vector_tostr(std::vector >)",引用
从:
main.o ld 中的 _main:未找到架构 x86_64collect2 的符号:错误:ld 返回 1 退出状态 make:*[主要] 错误1
不允许以与普通函数相同的方式分离模板化函数的声明和定义(声明在“.hpp”文件中,定义在“.cpp”文件中)。有几种方法可以解决这个问题。
您可以在头文件中的同一位置声明并定义该函数。
OR
你可以在一个名为的文件中尝试这个functions.inl
:
template<typename T>
inline string vector_tostr(std::vector<T> v){
std::stringstream ss;
std::string thestring = "";
if(v.size() > 0){
ss << "[";
for(size_t i = 0; i < v.size(); i++){
if(i != 0)
ss << " ";
ss << v[i];
}
ss << "]";
thestring = ss.str();
}
return thestring;
}
然后,在头文件的末尾(functions.hpp
),输入:
#include "functions.inl"
.inl
是内联头文件的文件扩展名。您可以使用它来分隔声明
以及模板化函数的定义。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)