C++ 函数模板,未定义的架构符号 [英] C++ Function Template, Undefined Symbol for Architecture

查看:30
本文介绍了C++ 函数模板,未定义的架构符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释为什么以下内容无法编译吗?希望我错过了明显的事情......

Can someone please explain to me why the following won't compile?, and hopefully the obvious thing that I have missed...

functions.hpp:

template<typename T> string vector_tostr(std::vector<T> v);

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;
}

ma​​in.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)
}

我得到的神秘错误如下:

The cryptic error I am getting as follows:

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

Undefined symbols for architecture x86_64: "std::basic_string, std::allocator > vector_tostr(std::vector >)", referenced from: _main in main.o ld: symbol(s) not found for architecture x86_64 collect2: error: ld returned 1 exit status make: * [main] Error 1

推荐答案

你不能像普通函数一样(在 '.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.

这篇关于C++ 函数模板,未定义的架构符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆