【问题标题】:Undefined reference from templated function (C++) [duplicate]来自模板函数的未定义引用(C++)[重复]
【发布时间】:2013-02-14 14:06:08
【问题描述】:
main.o: In function `main':
main.cpp:(.text+0x2f): undefined reference to `Foo<int>::display(int)'
collect2: ld returned 1 exit status

引起

g++ -c *.cpp && g++ *.o -o foo

foo.hpp:

#ifndef FOO_H_
#define FOO_H_

template<typename T>
class Foo {
  private:
    T ft_;
  public:
    Foo(const T & ft) : ft_(ft) { }
    Foo display(T x);
};

#endif

foo.cpp

#include "foo.hpp"
#include<iostream>
using namespace std;

template<typename T>
Foo<T> Foo<T>::display(T x) {
  // do some stuff - not too relevant
  cout << "[" << x << "]";
  Foo<T> res(x);
  return res;
}

main.cpp:

#include<iostream>
#include "foo.hpp"
using namespace std;

int main() {
  Foo<int> f(42);
  Foo<int> g = f.display(39);
  return 0;
}

为什么?!

P. S. 使用内联函数定义。每当函数的声明和定义被分成两个文件时,麻烦就来了...

【问题讨论】:

标签: c++ templates undefined linker-errors definition


【解决方案1】:

在 C++ 中,你需要将模板化方法和函数的定义放入头文件中。

【讨论】:

  • 那么在 C++11 中呢?
  • @LightnessRacesinOrbit 嗯,我似乎对外部模板的含义感到困惑......我认为有人建议可以在.cpp 文件中定义模板并认为它已经进入。从回答。
  • 也许您正在考虑 export,它实际上已从 C++11 中删除,但无论如何都没有用。
  • 谢谢!这让我很困惑,因为我在我的一本 C++ 书中看到它以这种方式使用...
猜你喜欢
  • 2014-04-30
  • 2012-05-24
  • 2012-02-03
  • 1970-01-01
  • 1970-01-01
  • 2015-10-12
相关资源
最近更新 更多