Rate This Document
Findability
Accuracy
Completeness
Readability

Template Class Instantiation Should Be Performed After Member Function Definition

Error Information

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;
}

An error is reported during linking.

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()'

Problem

If the instantiation of a template class is before the definition of a class member function, the template class instance does not contain the definition of this function.

Solution

  • Move the instantiation of the template class after the function definition.
  • Use the clang-tidy tool to identify such issues and provide modification suggestions.