gpt4 book ai didi

c++ - 当我将带有非模板类的模板类放在同一个 cpp 文件中时出现链接错误 - C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:24:01 24 4
gpt4 key购买 nike

当我在同一个 .cpp 文件中包含模板化和非模板化类时,出现链接时问题。

我查看了 C++ FAQ 35.13、35.14、35.15,但没有解决问题。

http://www.parashift.com/c++-faq-lite/separate-template-class-defn-from-decl.html

我正在使用带有 clang 的 Xcode 5。

举个例子

barfoo.h

class bar{
public:
void barfunc();
};

template <class T>
class foo{
public:
void foofunc();
};

这是cpp文件:

barfoo.cpp

void bar::barfunc(){...my code...}
template <class T>
void foo<T>::foofunc() {...my code...}
//I also put a instance of template class foo in the .cpp file
template class foo<int>;
//But is still generates the link error

错误是

clang: error: linker command failed with exit code 1 (use -v to see invocation)

但是当我删除 bar 类时,错误消失了,谁能告诉我为什么会产生这个错误?

将定义放在头文件中可以解决问题,但可能会导致另一个问题,即代码膨胀,谁能给出其他解决方案?

最佳答案

我发现了问题,问题是我没有将模板类实例化为我在代码中使用的类型。

下面是解决模板实例化问题的方案:

  1. Put definition in header file so the compiler will have the instance information. (disadvantage, increase the loading and compiling time)

  2. Instantiate all types that using in the code

关于c++ - 当我将带有非模板类的模板类放在同一个 cpp 文件中时出现链接错误 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21893346/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com