0

我有一个类需要在各种不同的上下文中调用外部函数。我想让事情变得灵活,所以我使用了一个接口(受第三版数字食谱的启发),它应该与仿函数、函数指针等一起使用。一个简化的示例如下所示:

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。关于这里可能发生的事情有什么想法吗?

谢谢,

——克雷格

4

1 回答 1

1

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

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

//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
于 2012-04-11T09:18:38.767 回答