首页 > 解决方案 > 我有三个 cpp 文件。我想在不同的文件中测试模板类声明和定义。但我失败了

问题描述

这是我的代码片段

// test.cpp
#include <iostream>
#include "test.h"
int main(){
  Test<int> test = Test<int>();

  test.add(1);
  test.print();
}

// test.h
#ifndef TEST
#define TEST
template <typename T> class Test{
public:
  T info;
  void print();
  void add(T i);
 };
#endif
// testT.cpp
#include <iostream>
#include "test.h"

template<typename T> void Test<T>::print()
{
   std::cout << info << std::endl;
}
template<typename T> void Test<T>::add(T i)
{
  info = i;
}

我运行这个 exec

g++ -c testT.cpp && g++ test.cpp -o a.out testT.o

我得到这个错误

Undefined symbols for architecture x86_64:
  "Test<int>::add(int)", referenced from:
      _main in test-e89092.o
  "Test<int>::print()", referenced from:
      _main in test-e89092.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)  // in my macOS

我想在头文件中声明模板类并在其他文件中定义方法,所以如果我更改模板类中方法的定义,我只编译定义方法文件而不是头文件。我应该怎么办?

标签: c++

解决方案


将模板分离为 cpp 和标头的一种可能方法是将其类型定义为您从定义函数主体的源中使用它的类型。

例如:在您的代码中,如果您将typedef Test<int> __UNUSED_TEMP_INT__;在 testT.cpp 的底部添加 a ,它将int在它识别主体的位置进行编译。但您只能将模板用于int.

其他选项是包含标头中的源,但 cpp 只是另一个标头。


推荐阅读