---
title: 模板类实例化应该在成员函数定义之后
description: "wrapper.h"
url: https://www.hikunpeng.com/document/detail/zh/kunpengdevps/compilation/ug-bisheng/kunpengbisheng_06_0096.html
sourcePath: /source/zh/kunpengdevps/compilation/ug-bisheng/kunpengbisheng_06_0096.html
indexId: e28042b782c475ef6892abd8371e9f67e7e21d975e9d2fc72d9e8b79a1e58b7074
---
# 模板类实例化应该在成员函数定义之后

#### 错误信息

wrapper.h

```
#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

```
#include "wrapper.h"
#include <iostream>
template <class T> void Wrapper<T>::print() {
  std::cout << x << std::endl;
}
```

main.cpp

```
#include "wrapper.h"
int main() {
  Wrapper<int> x(10);
  x.print();
  return 0;
}
```

链接时报错

```
$ clang++ wrapper.cpp main.cpp -w
/usr/bin/ld: in function `main':
main.cpp:(.text+0x3c): undefined reference to `Wrapper<int>::print()'
```


#### 问题介绍

若模板类的实例化在类成员函数定义之前，则该模板类实例中不包含这个函数的定义。


#### 解决方案

- 将模板类实例化移动到函数定义之后；
- 使用clang-tidy工具可以识别该类问题并提供修改建议。
