c++ - 使用模板链接错误

标签 c++ templates linkage

我将函数转换为模板,然后开始出现此错误。我不能理解模板的限制。谁能告诉我为什么它坏了?

我收到这个错误:

Undefined symbols:
  "bool foo<int>(int const&, int const&)", referenced from:
      _main in file1.o
ld: symbol(s) not found

当我链接以下代码时。代码被简化了,但仍然失败。第一个文件包含:

#include <iostream>
template <class T> bool foo (const T&, const T&);

int main ()
{
  int left = 1;
  int right = 2;

  if (foo <int> (left, right))
    std::cout << "foo!" << std::endl;

  return 0;
}

第二个文件包含:

template <class T> bool foo (const T& left, const T& right)
{
  return true;
}

最佳答案

Uri给出的原因,模板方法通常定义在头文件中。因为你的是一个函数而不是一个类的方法,所以明确地将它定义为静态或内联(在可能被多个 CPP 文件包含的头文件中)。

把它放在你的 foo.h 中

template<class T> inline bool foo (const T& left, const T& right)
{
  return true;
}

把这个放在你的 main.cpp 中

#include <iostream>
#include "foo.h"

int main ()
{
  int left = 1;
  int right = 2;

  if (foo <int> (left, right))
    std::cout << "foo!" << std::endl;

  return 0;
}

cpp 代码现在可以看到模板函数的整个声明。

此处列出了其他解决方案:How can I avoid linker errors with my template functions?

关于c++ - 使用模板链接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/550219/

相关文章:

c++ - 解释基数排序

c++ - n维 vector

c++ - 重新审视 switch 内部的对象实例化 (c++)

c++ - 在cpp中定义模板特化?

c++ - 未解析的外部符号 “std::basic_string”

c++ - 在编译时检查函数是否有外部链接

c++ - 顶点着色器后的 OpenGL 三角形退化?

c++ - ipv4存储的数据结构+算法——高效的前缀搜索

c++ - 为什么不同 block 中相同命名的外部局部变量在 C++ 中的编译器之间获得不同的链接?

c++ - 初级 C++ 类型混淆