我正在尝试创建一个对象列表,其中每个对象还存储“所有权”——即,它知道哪个列表拥有它。
在非模板情况下,很简单:
class FooList; // forward declaration
class FooItem
{
public:
FooList *owner;
...
};
class FooList: private std::list<FooItem>
{
...
};
但是,列表类是一个模板,基于包含的对象类型,我正在努力弄清楚如何指定它。我认为 FooItem 类现在需要是一个模板,因为“所有者”的类型可能会有所不同:
template <class E> class FooItem
{
public:
std::list<E> *owner;
};
template <class E> class FooList: private std::list<E>
{
...
};
但是,现在有了我的两个模板,我该如何定义我想要的新类型呢?下面的代码片段是我认为我需要的,但它给出了 "error: Multiple declaration for BarItem"
.
class BarItem;
typedef FooList<BarItem> BarList;
typedef FooItem<BarList> BarItem;
编辑:
感谢指出std::list<E>
问题的人而不是 std::list<FooItem<E> >
编辑 2:
将类重命名为 Base, Derived, BaseList, DerivedList.
我真正的问题是“循环类型定义”。经过一些修补后,我认为这将满足我的要求。它创建了一个“真正的”BarItem 类,而不仅仅是一个 typedef,但现在似乎至少可以编译了。
template <class E> class BaseList; // forward declaration
template <class E> class Base
{
public:
BaseList< Base<E> > *owner;
};
template <class E> class BaseList: private std::list< E >
{
};
// typedef Base<BaseList<Derived> > Derived; //This won't compile, unsurprisingly.
class Derived : public Base < BaseList<Derived> > // Surprisingly, this seems to.
{
...
};
typedef BaseList<Derived> DerivedList;
这看起来有道理吗?它是常见的成语还是可怕的东西?
最佳答案
你确定你不想:
template <class E> class FooItem
{
public:
std::list< FooItem<E> > *owner; // owned by a list of FooItem<E>, not raw E
};
template <class E> class FooList: private std::list< FooItem<E> > // is a list of FooItem<E>, not raw E
{
...
};
您遇到的错误是因为您前向声明了类 BarItem
但稍后尝试使用 typedef
重新定义该名称。不确定您要完成什么,但您需要介绍第三个名字。也许你的意思是:
class Bar;
typedef FooItem<Bar> BarItem;
typedef FooList<Bar> BarList;
编辑:您发布的新代码当然可以编译,但看起来很笨拙(一方面,命名看起来真的很困惑)。也许您应该提出一个新问题,并提供一个更具体的示例,说明为什么您认为您需要一个“本身就是列表项的项目”,然后看看其他人是否可以提出一个不那么尴尬的设计。
关于c++ - C++ 中模板化对象的模板化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3442108/