Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error compiling Function templates with C++ [duplicate]

Tags:

c++

c++11

Possible Duplicate:
Why can templates only be implemented in the header file?

I'm getting some errors in gcc and clang that I'm not familiar with. First off, here's the code in question.

WaypointTree.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() {}
};

WaypointTree.cpp:

. . .

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

. . .

Flock.cpp:

. . .

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

. . .

With clang, I get the following warning:

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) {
                    ^

Followed by the following linker error:

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)'

With gcc I get only the following error :

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]

I'm not really sure where to begin debugging this, but it seems to be related to the templates and the lambdas.

like image 557
gregghz Avatar asked Jun 11 '26 00:06

gregghz


1 Answers

You have to implement your template functions in the .h file, not in the .cpp

Here's some further reading

like image 171
Foggzie Avatar answered Jun 12 '26 14:06

Foggzie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!