与模板类的链接错误
Linking error with template classes
我有一个类,需要在各种不同的上下文中调用外部函数。 我想保持灵活性,所以我使用了一个界面(灵感来自第 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
相关文章:
- 静态数据成员的问题-修复链接错误会导致编译器错误
- Visual Studio mkl_link_tool.exe链接错误
- C++ 实现模板单例类时出现链接错误
- 使用类模板的方法链接错误
- MySQL C++连接器链接错误
- VS 2015 链接错误 无法构建依赖于 libcurl 的项目
- 运行 C++ 单元测试时LNK2005链接错误
- 对 CMake 中'cudaRegisterLinkedBinary'链接错误的未定义引用?
- 链接错误,包括我创建的相同头文件 - C++
- 在Embarcadero C++ Builder中生成的DLL未解决的外部链接错误
- 使用标头保护的多个定义链接错误
- 链接错误:未定义对 stdscr 和 wgetch 的引用
- 使用 Vivek 的 Vcam / 捕获源过滤器构建/链接错误
- 升压program_options中的链接错误
- 使用 g++ 预处理器进行替换会导致链接错误
- 在调试配置中编译工作正常,但发布会给出链接错误
- 相邻矩阵设置链接错误
- 包含常量变量并包含在多个文件中的标头的链接错误
- C++链接错误,我理解但无法解决
- 是什么导致macOS Mojave上的GoogleTest链接错误