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

标签 c++ linker-errors template-classes

当我在同一个 .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/

相关文章:

c++ - 如何发现金额计算中的错误

Cuda C - 链接器错误 - undefined reference

c++ - 一个类可以继承自另一个具体化的类模板吗?

c++ - 如何正确使用模板类的嵌套类?

c++ - 为什么我会收到 Unresolved external 问题?

c++ - g++ "declaration of "运算符<<"as non-function"

c - Linux 的动态链接器 : how to call a function from the main process from an . 所以对象?

c++ - 这个简单的 C++ 模板类有什么问题?

c++ - cpp 文件中是否需要 __declspec(dllexport)

c++ - 将函数 erf() 和 erfc() 添加到 math.h _ C 的基础知识。