更改给定 STL 容器的 value_type
假设我有一个 STL 容器类型(不是对象),例如vector
。现在它的value_type
是A
,所以我想把它改为B
。
基本上,我想要一个这种形式的类模板,或其变体:
template<typename container, typename new_value_type>
struct change_value_type
{
typedef /*....*/ new_container;
};
这样我就可以按以下方式使用它:
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
是否可以?
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
Means, new_container
is vector<B>
Is it possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当我试图从本质上解决同样的问题时,偶然发现了这一点。它甚至可以在不依赖于
std::allocator
特定的rebind
类型的情况下工作 - 唯一的要求是反弹值类型是各个类的第一个模板参数。所有相关的 STL 类(std::vector
、std::set
、std::list
等以及例如std::less
和std::allocator
)。C++11 之前的解决方案如下所示:
C++11 让它变得更简单:
为了支持
std::array
,可以添加以下内容:结果可以使用几乎任何 STL 类型:
在 Linux 系统上运行它并通过
c++filt -t
管道输出可以为您提供Just stumbled over this as I was trying to essentially solve the same problem. It can even be made to work without relying on the
rebind
type that is specific tostd::allocator
– the only requirement is that the rebound value type is the first template parameter of the respective classes. This is the case for all relevant STL classes (std::vector
,std::set
,std::list
etc. as well as for examplestd::less
andstd::allocator
).A pre-C++11 solution would look like this:
C++11 makes it a bit easier:
In order to support
std::array
, the following can be added:The result can be used with just about any STL type:
Running this and piping the output through
c++filt -t
on a Linux system gives you您可以尝试专门使用模板模板参数。
但是,容器可能没有这两个模板参数。
此外,在容器适配器和关联容器中,不仅仅是分配器需要替换(适配器中的底层容器、std::set 中的谓词)。 OTOH,它们的用法与序列容器如此不同,以至于很难想象一个适用于任何容器类型的模板。
You might try specializing with template template parameters.
However, containers might not have those two template parameters.
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.您指的是(我相信)策略克隆惯用语,使用重新绑定
You're referring (I believe) to the Policy Clone idiom, using rebind