更改给定 STL 容器的 value_type

Changing value_type of a given STL container(更改给定 STL 容器的 value_type)

本文介绍了更改给定 STL 容器的 value_type的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设,我有一个 STL 容器 type(不是对象),比如 vector.现在它的 value_typeA,所以我想把它改成 B.

Suppose, I've a STL container type (not object), say vector<A>. Now it's value_type is A, so I want to change it to B.

基本上,我想要一个这种形式的类模板,或者它的变体:

Basically, I want a class template of this form, or a variant of it:

template<typename container, typename new_value_type>
struct change_value_type
{
    typedef /*....*/  new_container;
};

以便我可以通过以下方式使用它:

So that I can use it in the following way:

typename change_value_type<vector<A>, B>::new_container  vectorOfB; 
vectorOfB.push_back(B());
vectorOfB.push_back(B());
vectorOfB.push_back(B());
//etc

意思是,new_container就是vector

有可能吗?

推荐答案

您可以尝试专门使用模板模板参数.

You might try specializing with template template parameters.

#include <vector>
#include <list>
#include <deque>
#include <string>

template <class T, class NewType>
struct rebind_sequence_container;

template <class ValueT, class Alloc, template <class, class> class Container, class NewType>
struct rebind_sequence_container<Container<ValueT, Alloc>, NewType >
{
     typedef Container<NewType, typename Alloc::template rebind<NewType>::other > type;
};

template <class Container, class NewType>
void test(const NewType& n)
{
    typename rebind_sequence_container<Container, NewType>::type c;
    c.push_back(n);
}

int main()
{
    std::string s;
    test<std::vector<int> >(s);
    test<std::list<int> >(s);
    test<std::deque<int> >(s);
}

但是,容器可能没有这两个模板参数.

However, containers might not have those two template parameters.

此外,在容器适配器和关联容器中,不仅需要替换分配器(适配器中的基础容器,std::set 中的谓词).OTOH,它们的用法与序列容器如此不同,以至于很难想象一个模板适用于任何容器类型.

Also, in container adapters and associative containers, not just the allocator would need replacing (underlying container in adapters, predicate in std::set). OTOH, their usage is so different from sequence containers that it is hard to imagine a template that works with any container type.

这篇关于更改给定 STL 容器的 value_type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:更改给定 STL 容器的 value_type