C++函数模板,体系结构的未定义符号

Nic*_*ton 5 c++ templates

有人可以向我解释为什么以下不会编译?,希望我错过了显而易见的事情......

functions.hpp:

template<typename T> string vector_tostr(std::vector<T> v);
Run Code Online (Sandbox Code Playgroud)

functions.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;
}
Run Code Online (Sandbox Code Playgroud)

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)
}
Run Code Online (Sandbox Code Playgroud)

我得到的神秘错误如下:

体系结构x86_64的未定义符号:"std :: basic_string,std :: allocator> vector_tostr(std :: vector>)",引用自:main.o中的_main ld:未找到体系结构x86_64的符号collect2:error: ld返回1退出状态make:* [main]错误1

Den*_*nis 5

不允许您以与普通函数相同的方式分离模板化函数的声明和定义(声明在“.hpp”文件中,定义在“.cpp”文件中)。有几种方法可以解决这个问题。

您可以在头文件中的同一位置声明和定义该函数。

或者

您可以在名为的文件中尝试此操作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;
}
Run Code Online (Sandbox Code Playgroud)

然后,在头文件 ( ) 的末尾functions.hpp键入:

#include "functions.inl"
Run Code Online (Sandbox Code Playgroud)

.inl是内联头文件的文件扩展名。您可以使用它来分隔模板化函数的声明和定义。

  • 然而你从“你不能将声明和定义分开......”开始。这实在是太误导人了! (2认同)