所有类型的 std::vector 的部分特化 [英] Partial specialization for std::vector of all types
问题描述
我不确定模板化是否走得太远,但存在以下问题:
I'm not sure whether I'm going too far with templateization, but the following problem:
我有一个容器类.这个类可以直接取值,也可以取带值的向量.我想专门针对第二种情况.
I have sort of a container class. This class can directly take values or it can take vectors which take values. I would like to specialize it for the second case.
我怎么能...
- ...将类专门用于任何类型的向量?
- ...在专门的类中提取向量的参数?
代码示例:
// GENERAL CASE with vector of type T
template <class T>
class Container
{
std::vector<T> container;
void set(T val, int idx){
this->container[idx] = val;
}
};
// SPECIAL CASE with vector of vectors
template <>
class Container<std::vector<all types allowed>>
{
std::vector<The_type_of_vector> container;
void set(The_type_of_vector val, int idx1, int idx2){
this->container[idx1][idx2] = val; // set element idx2 in vector idx1
}
};
(当然我的 Container 比这里显示的要复杂一些.我也可以创建两个不同的非模板版本的容器.但仔细想想,我也很好奇我如何通过专业化来做到这一点.)
(Of course my Container is a bit more complicated than shown here. I could also create two different non-template versions of the container. But after thinking about it, I'm also curious how I could do it with specialization.)
推荐答案
大功告成,您只需要语法即可.
You're almost there, all you need is the syntax.
// SPECIAL CASE with vector of vectors
template < typename element_type >
class Container<std::vector< element_type >>
如果你真的想支持不同的分配器,你也可以从 vector
中提取分配器类型.
You could also extract the allocator type from vector
, if you actually want to support different allocators.
我不确定我是否在模板化方面做得太过分
I'm not sure whether I'm going too far with templateization
如果您可以选择是否编写模板,通常您不应该这样做.否则,这里没有任何可疑之处.
If you have a choice between writing a template or not, usually you shouldn't. Otherwise, nothing here is suspicious.
这篇关于所有类型的 std::vector 的部分特化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!