我有三个cpp文件。我想在不同的文件中测试模板类声明和定义。但是我失败了[重复]

问题描述 投票:-4回答:1

这是我的代码片段

// 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

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

c++
1个回答
0
投票

将模板分隔为cpp和header的一种可能方法是将typedef设置为从定义函数体的源中使用它的类型。

例如:在你的代码中,如果你在testT.cpp的底部添加一个typedef Test<int> __UNUSED_TEMP_INT__;,它将在一个识别物体的地方为int编译。但是你只能将模板用于int

其他选项是从头部包含源,但cpp只是另一个头。

© www.soinside.com 2019 - 2024. All rights reserved.