可能重复:
Why can templates only be implemented in the header file?
我在gcc和clang中遇到一些我不熟悉的错误。首先,这是有问题的代码。
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();
});
。 。
有了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有关。
答案 0 :(得分:7)
您必须在.h文件中实现模板函数,而不是在.cpp
中答案 1 :(得分:2)
编译器需要WaypointTree.cpp
中的定义才能生成_waypoints->foreach([] (Waypoint *wp)
的代码。因此,您必须同时包含cpp或在头文件中定义foreach
。