2

可能重复:
为什么模板只能在头文件中实现?

我在 gcc 和 clang 中遇到了一些我不熟悉的错误。首先,这是有问题的代码。

航点树.h:

class WaypointTree {

 private:
  Waypoint *head = nullptr;
  Waypoint *current = nullptr;
  template<class Function>
    void each_recur(Waypoint *current, Function f);

 public:
  template<class Function>
    void foreach(Function f);
  void add(Waypoint *wp, Waypoint *parent = nullptr);
  bool isLast(Waypoint *wp);
  Waypoint *next();
  Waypoint *getHead() { return head; }
  void reverse() {}
};

航点树.cpp:

. . .

template<class Function>
void WaypointTree::foreach(Function f) {
  each_recur(head, f);
}

. . .

群.cpp:

. . .

_waypoints->foreach([] (Waypoint *wp) {
        glPushMatrix(); {
          glTranslatef(wp->getX(), wp->getY(), wp->getZ());
          glutSolidSphere(0.02, 5, 5);
        } glPopMatrix();
      });

. . .

使用clang,我收到以下警告:

lib/WaypointTree.h:17:7: warning: function 'WaypointTree::foreach<<lambda at lib/Flock.cpp:128:22> >' has internal linkage but is not defined
        void foreach(Function f);
             ^
lib/Flock.cpp:128:14: note: used here
        _waypoints->foreach([] (Waypoint *wp) {
                    ^

随后出现以下链接器错误:

lib/Flock.cpp:128: error: undefined reference to 'void WaypointTree::foreach<Flock::render(std::vector<Boid*, std::allocator<Boid*> >)::$_3>(Flock::render(std::vector<Boid*, std::all
ocator<Boid*> >)::$_3)'

使用 gcc 我只收到以下错误:

lib/WaypointTree.h:17:7: error: ‘void WaypointTree::foreach(Function) [with Function = Flock::render(std::vector<Boid*>)::<lambda(Waypoint*)>]’, declared using local type ‘Flock::ren
der(std::vector<Boid*>)::<lambda(Waypoint*)>’, is used but never defined [-fpermissive]

我不确定从哪里开始调试它,但它似乎与模板和 lambdas 有关。

4

2 回答 2

7

您必须在 .h 文件中实现模板函数,而不是在 .cpp 中

这里有一些进一步的阅读

于 2012-12-31T19:39:25.397 回答
2

编译器需要定义WaypointTree.cpp才能生成_waypoints->foreach([] (Waypoint *wp). 因此,您必须同时包含您的 cpp 或foreach在头文件中定义。

于 2012-12-31T19:40:51.577 回答