更新时间:2023-11-09 14:40:28
你不能像普通函数一样(在 '.hpp' 文件中声明,'.cpp' 文件中的定义).有几种方法可以解决这个问题.
You are not allowed to seperate the declaration and definition of a templated function in the same way that you would a normal function (declaration in '.hpp' file, definition in '.cpp' file). There are a couple of ways you can get around that.
您可以在头文件的同一位置声明和定义函数.
You can declare AND define the function in the same place in the header file.
或
您可以在名为 functions.inl
的文件中尝试此操作:
You could try this, in a file called 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
)的末尾,输入:
Then, at the end of the header file (functions.hpp
), type this in:
#include "functions.inl"
.inl
是内联头文件的文件扩展名.您可以使用它来分隔声明以及模板化函数的定义.
.inl
is the file extension for the inline header file. You can use this to seperate the declaration
and definition of templated functions.