加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

您可以使用C模板指定集合类型和该类型的特化吗?

发布时间:2020-12-16 10:55:25 所属栏目:百科 来源:网络整理
导读:例如,我想将一个类专门化为一个成员变量,它是一个stl容器,比如一个向量或一个列表,所以我需要这样的东西: template class CollectionType,class ItemTypeclass Test{public: CollectionTypeItemType m_collection;}; 所以我可以这样做: Test t = Testvecto
例如,我想将一个类专门化为一个成员变量,它是一个stl容器,比如一个向量或一个列表,所以我需要这样的东西:

template <class CollectionType,class ItemType>
class Test
{
public:
    CollectionType<ItemType> m_collection;
};

所以我可以这样做:

Test  t = Test<vector,int>();
t.m_collection<vector<int>> = vector<int>();

但这会产生

test.cpp:12: error: `CollectionType' is not a template

解决方法

为什么不这样做呢?

template <class CollectionType>
class Test
{
public:
    CollectionType m_collection;
};

Test  t = Test<vector<int> >();
t.m_collection = vector<int>();

如果需要itemtype,可以使用CollectionType :: value_type.

编辑:响应您关于创建返回value_type的成员函数的问题,您可以这样做:

typename CollectionType::value_type foo();

您添加了typename,因为CollectionType尚未绑定到实际类型.所以它没有可以查找的value_type.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读