解决模板类之间的循环依赖关系
我有两个类,Foo
和 Bar
,派生自 Base
。每个都重写方法 virtual Base* Convert(ID) const
,其中 ID
是唯一标识 Foo
特定实例的类型实例或 Bar
(假设它是一个 enum
)。问题是 Foo::convert()
需要能够返回一个 Bar
实例,同样 Bar::convert()
需要能够实例化 Foo
。由于它们都是模板,因此会导致 Foo.h
和 Bar.h
之间出现循环依赖关系。我该如何解决这个问题?
编辑:前向声明不起作用,因为每个方法的实现都需要另一个类的构造函数:
Foo.h
:
#include <Base.h>
template<class T> class Bar;
template<class T>
class Foo : public Base { ... };
template<class T>
Base* Foo<T>::convert(ID id) const {
if (id == BAR_INT)
return new Bar<int>(value); // Error.
...
}
Bar.h
:
#include <Base.h>
template<class T> class Foo;
template<class T>
class Bar : public Base { ... };
template<class T>
Base* Bar<T>::convert(ID id) const {
if (id == FOO_FLOAT)
return new Foo<float>(value); // Error.
...
}
错误自然是“无效使用不完整类型”。
I have two classes, Foo<T>
and Bar<T>
, derived from Base
. Each overrides a method virtual Base* convert(ID) const
, where ID
is an instance of a type that uniquely identifies a particular instantiation of Foo
or Bar
(pretend it's an enum
). The problem is that Foo::convert()
needs to be able to return a Bar
instance, and likewise Bar::convert()
needs to be able to instantiate Foo
. Since they're both templates, this results in a circular dependency between Foo.h
and Bar.h
. How do I resolve this?
Edit: A forward declaration does not work because the implementation of each method needs the constructor of the other class:
Foo.h
:
#include <Base.h>
template<class T> class Bar;
template<class T>
class Foo : public Base { ... };
template<class T>
Base* Foo<T>::convert(ID id) const {
if (id == BAR_INT)
return new Bar<int>(value); // Error.
...
}
Bar.h
:
#include <Base.h>
template<class T> class Foo;
template<class T>
class Bar : public Base { ... };
template<class T>
Base* Bar<T>::convert(ID id) const {
if (id == FOO_FLOAT)
return new Foo<float>(value); // Error.
...
}
The error is, naturally, "invalid use of incomplete type".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要做的是将类声明与实现分开。这样
,在定义函数时,您就拥有完整的类定义。
What you need to do is seperate the class declarations from the implementation. So something like
This way, you have complete class definitions when the functions are defined.
(更新)
您应该能够像处理非模板类一样处理该问题。像这样写你的Bar.h。 (对于 Foo.h 也是如此)
(Updated)
You should be able to handle that the same as with non-template classes. Write your Bar.h like this. (And similarly for Foo.h)
您应该在任一标头中使用模板类前向声明,
这是非常好的模板类前向声明。
You should use template class forward declarations in either headers
is perfectly good template class forward declaration.
詹姆斯·柯兰的回答是天赐之物。一般来说,James 的想法是限制包含所需的头文件,直到需要来自包含的头文件的成员('声明)为止。例如:
t1.hh
t2.hh
t.cc
James Curran's answer is a godsend. Generally speaking, James' idea is to restrict inclusion of required header files until the moment the members(' declarations) coming from included header files are needed. As an example:
t1.hh
t2.hh
t.cc