与模板类的链接错误

Linking error with template classes

本文关键字:链接 错误      更新时间:2023-10-16

我有一个类,需要在各种不同的上下文中调用外部函数。 我想保持灵活性,所以我使用了一个界面(灵感来自第 3 版的数字配方),它应该与函子、函数指针等一起使用。 一个简化的示例如下所示:

class MyClass {
  public:
    template <class T>
    MyClass(T &f_) { f = f_; }
  private:
    int (*f)(int);
};
int myFn(int i) {
  return i % 100;
}
int main() {
  MyClass test(myFn);
  return 0;
}

到目前为止一切顺利;g++编译它没有任何抱怨。 在我的实际应用程序中,有更多的代码,所以我把东西分成了多个文件。 例如

测试2.h:

#ifndef __test2__
#define __test2__
class MyClass {
  public:
    template <class T>
    MyClass(T &f_);    
 private:
    int (*f)(int);
};
#endif

测试2.cpp:

#include "test2.h"
template <class T>
MyClass::MyClass(T &f_) {
  f = f_;
}

主.cpp:

#include "test2.h"
int myFn(int i) {
  return i % 100;
}
int main() {
  MyClass test(myFn);
  return 0;
}

当我尝试使用 g++ test2.cpp main.cpp 编译它时,出现以下链接错误:

/tmp/ccX02soo.o: In function 'main':
main.cpp:(.text+0x43): undefined reference to `MyClass::MyClass<int ()(int)>(int (&)(int))'
collect2: ld returned 1 exit status

看起来 g++ 不知道我也在尝试编译 test2.cpp。 关于这里可能发生的事情的任何想法?

谢谢

--克雷格

模板类的实现必须对所有使用它们的翻译单元可见,除非它们是完全专用的。

这意味着您必须在标头中移动实现:

//test2.h
#ifndef __test2__
#define __test2__
class MyClass {
  public:
    template <class T>
    MyClass(T &f_);    
 private:
    int (*f)(int);
};
template <class T>
MyClass::MyClass(T &f_) {
  f = f_;
}
#endif