如何在头文件中声明 class 模板(由于循环依赖)
how to declare class template in header file (due of circular dependencies)
有
Bar.h
template<class T>
class Bar<T> {
//...
}
Foo.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 中编写实现
但是这个例子我有一些问题,因为我不知道 class with template..
的语法
这有什么语法吗?
当前示例出现以下编译器错误:
Bar is not a class template
前向声明语法是
template<T> class Bar;
因此您的代码变为:
Foo.h
template<T> class Bar;
template<class T>
class Foo {
...
private:
Bar<T> *_bar;
};
#include "Foo.inl"
Foo.inl
#include "bar.h"
// Foo implementation ...
Bar.h
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;
};
有
Bar.h
template<class T>
class Bar<T> {
//...
}
Foo.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 中编写实现 但是这个例子我有一些问题,因为我不知道 class with template..
的语法这有什么语法吗? 当前示例出现以下编译器错误:
Bar is not a class template
前向声明语法是
template<T> class Bar;
因此您的代码变为:
Foo.h
template<T> class Bar;
template<class T>
class Foo {
...
private:
Bar<T> *_bar;
};
#include "Foo.inl"
Foo.inl
#include "bar.h"
// Foo implementation ...
Bar.h
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;
};