C++中模板的循环引用
在 C# 中考虑这样的事情:
class C<T> {}
class D : C<E> {}
class E : C<D> {}
是否可以使用模板在 C++ 中进行等效构造?
回答
是的,您可以转发声明E:
template <typename T> class C {};
class E;
class D : public C<E> {};
class E : public C<D> {};
或者,根据弗兰克斯的建议:
template <typename T> class C {};
class D : public C<class E> {};
class E : public C<D> {};
这在您的实际情况中是否有效取决于是否C需要T完成(在这个精简的示例中没有)。
PS:我不懂 C#,所以我不确定你是想要私有继承还是公共继承。上面使用了公共继承,而使用关键字声明的类的默认值class是私有继承。
- Agreed that it's a matter of style. I personally like it because it makes it explicit that the type is expected to not be complete. Unlike a regular template that may or may not be inheriting from a complete type depending on stuff that's headers away.
- @markonius thats no reason to not close it as duplicate. A question getting closed as duplicate is not the same as a question getting deleted. Often duplicates make good entry points for future readers, though the answer needs to be at only one place. This answer here really does not add much to the one you can already find elsewhere