模板类实例化应该在成员函数定义之后
错误信息
wrapper.h
1 2 3 4 5 6 7 8 9 10 11 12 | #ifndef WRAPPER_H #define WRAPPER_H template <class T> class Wrapper { public: Wrapper() = default; Wrapper(const T &t) : x(t) {} void print(); private: T x; }; template class Wrapper<int>; #endif |
wrapper.cpp
1 2 3 4 5 | #include "wrapper.h" #include <iostream> template <class T> void Wrapper<T>::print() { std::cout << x << std::endl; } |
main.cpp
1 2 3 4 5 6 | #include "wrapper.h" int main() { Wrapper<int> x(10); x.print(); return 0; } |
链接时报错
1 2 3 | $ clang++ wrapper.cpp main.cpp -w /usr/bin/ld: in function `main': main.cpp:(.text+0x3c): undefined reference to `Wrapper<int>::print()' |
问题介绍
若模板类的实例化在类成员函数定义之前,则该模板类实例中不包含这个函数的定义。
解决方案
- 将模板类实例化移动到函数定义之后;
- 使用clang-tidy工具可以识别该类问题并提供修改建议。
父主题: 其它类兼容问题