更改给定STL容器的value_type [英] Changing value_type of a given STL container
问题描述
假设,我有一个STL容器 type (不是对象),例如vector<A>
.现在它的value_type
是A
,所以我想将其更改为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<B>
有可能吗?
推荐答案
您可以尝试专门使用模板模板参数.
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!