【发布时间】:2011-02-10 20:50:10
【问题描述】:
以下代码表示基于std::vector的容器
template <typename Item>
struct TList
{
typedef std::vector <Item> Type;
};
template <typename Item>
class List
{
private
typename TList <Item>::Type items;
....
}
int main()
{
List <Object> list;
}
是否可以将 std::vector 模板化并创建一个通用容器,类似的东西?
template <typename Item, typename stl_container>
struct TList
{
typedef stl_container<Item>;
};
其中 stl_container 代表 std::vector、std::list、std::set...?我想在创建时选择容器的类型。
List <Object, std::vector> list; //vector of objects, not a real code
List <Object, std::vector> list; //list of objects, not a real code
感谢您的回答...
更新问题:
我尝试了以下代码但有错误:
#include <vector>
template <typename Item, typename Container>
struct TList
{
typedef typename Container <Item>::type type; //Error C2059: syntax error : '<', Error C2238: unexpected token(s) preceding ';
};
template <typename T>
struct vector_container
{
typedef std::vector<T> type;
};
int _tmain(int argc, _TCHAR* argv[])
{
TList <int, vector_container> v;
TList <int, map_container> m;
}
【问题讨论】:
-
谁会使用这个类?为什么
List不能只使用typedef vector/list/set<Item> items?在给定容器类型和值类型的情况下,将这两者简单地放在一起的类的目的是什么? -
Re: 编辑,还是不明白为什么不能写
List<std::vector<Object> > list;等