【问题标题】:Link error when I put template class with non-template classes in same cpp file - C++当我将模板类与非模板类放在同一个 cpp 文件中时出现链接错误 - C++
【发布时间】:2014-02-19 21:55:28
【问题描述】:

当我在同一个 .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: 链接器命令失败,退出代码为 1(使用 -v 查看调用)

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

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

【问题讨论】:

  • 实例化没有帮助。您不能将适用于所有 T 的定义放在不同的翻译单元中。
  • 感谢您的快速响应,那么我应该怎么做才能避免这个错误呢?
  • 如果你为所有T定义它,它需要放在标题中或以其他方式包含在标题中(例如,标题包括底部的定义文件)。
  • 也就是说,将方法foofunc的定义也放入头部。

标签: c++ linker-errors template-classes


【解决方案1】:

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

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

  1. 将定义放在头文件中,以便编译器获得实例信息。 (缺点,增加加载和编译时间)

  2. 实例化代码中使用的所有类型

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    • 2020-08-23
    相关资源
    最近更新 更多