如何在头文件中声明类模板(由于循环依赖关系)

how to declare class template in header file (due of circular dependencies)

本文关键字:于循环 循环 关系 依赖 文件 声明      更新时间:2023-10-16

拥有

酒吧

template<class T>
class Bar<T> {
//...
}

福.h

template<T>
class Bar<T>;
//#include "Bar.h" removed due of circular dependencies, I include it in .cpp file
template<class T>
class Foo {
...
private:
Bar<T> *_bar;
}

如您所见,我需要包含 bar.h,但由于循环依赖原因,我无法在我的项目中执行此操作。

因此,就像我通常所做的那样,我只是用.h编写定义,用.cpp实现 但是我对这个例子有一些问题,因为我不知道带有模板的类的语法。

这有什么语法吗? 当前示例出现以下编译器错误:

Bar is not a class template

前向声明语法为

template<T> class Bar;

因此,您的代码变为:

福.h

template<T> class Bar;
template<class T>
class Foo {
...
private:
Bar<T> *_bar;
};
#include "Foo.inl"

福.inl

#include "bar.h"
// Foo implementation ...

酒吧

template<class T>
class Bar<T> {
//...
};

您的示例没有循环依赖项。Bar不以任何方式依赖于Foo。您可以按以下顺序定义模板:

template<class T> class Bar {};
template<class T>
class Foo {
private:
Bar<T> *_bar;
};

如果您希望将定义分成两个文件,则可以像这样实现上述排序:

// bar:
template<class T>
class Bar {};
// foo:
#include "bar"
template<class T>
class Foo {
private:
Bar<T> *_bar;
};