【问题标题】:the template class in one header file cant find the other template class in another header file一个头文件中的模板类在另一个头文件中找不到另一个模板类
【发布时间】:2022-06-10 23:18:47
【问题描述】:

我正在尝试用 C++ 编写一段代码,为了使事情变得整洁,我决定将源代码拆分为文件。所以基本上每个头文件都包含类及其字段和方法的声明,在底部,它包含一个包含所有实现的 .cpp 文件。我不得不做一个非常奇怪的行为,在标题之后包含源代码,因为我正在使用模板类,我必须这样做来修复链接器错误。

不管怎样,代码看起来是这样的:

common/vec3.h:

#ifndef
#define protector blah blah

template<class T>
class vec3{
//
// fields and methods
// int bruh
// double func(vec3<T>);
//
};
#include "vec3.cpp"
#endif

在 common/vec3.cpp 中我只实现了 vec3.h 中声明的函数:

//=========vec3============

template <class T>
double vec3<T>::func(vec3<T> v){
//...
}
//...

common/dir3.h:

#ifndef
#define protector blah blah

template<class T>
class dir3{
//
//
//
void operator=(vec3<T>); // this line is causing error
//
//
};
#include "dir3.cpp"
#endif

common/dir3.cpp:

//======dir3===========
//
//
//
template<class T>
void dir3<T>::operator=(vec3<T> v){
// ...
}
//
//

在我的主文件中,我包含以下库:

#include <iostream>
#include <list>
// ...
using namespace std;
#include "common/vec3.h"
#include "common/dir3.h"
// ...
int main(){
//...
}

但是当我尝试用

编译这个项目时

g++ main.cpp -o main

我得到错误:

In file included from main.cpp:8:0:
common/dir3.h:14:17: error: 'vec3' is not a type
  void operator=(vec3<T>);
                 ^

即使我在vec3.h 之后包含了dir3.h,并且它们都有模板类定义。 我知道类和模板类之间差异的细微差别在某种程度上,但我看不到在另一个模板类中使用模板类的任何其他方式(它不需要实例化)。

我什至尝试在dir3.h 文件中包含vec3.h 文件,但没有成功。

为什么这不起作用,我该怎么办?

【问题讨论】:

  • 为什么要包含源文件?!!就像你在给定的例子中一样#include "dir3.cpp"

标签: c++ class templates


猜你喜欢
  • 2011-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-06
  • 1970-01-01
  • 1970-01-01
  • 2019-11-18
  • 1970-01-01
相关资源
最近更新 更多