2014-12-02 34 views
1

我不知道我是否会与templateization太远的载体,但以下问题:性病偏特::各类

我有某种容器类的。这个类可以直接取值,也可以取值为向量。我想专门针对第二种情况。

我怎么能......

  1. ...专门用于任何类型的载体类?
  2. ...提取专业类中的矢量参数?

代码例如:。

// 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 
     } 

}; 

(当然我的容器是一个有点比这里显示更复杂的我还可以创建容器的两个不同的非模板版本,但经过考虑之后,我也很好奇我怎样才能做到这一点)

回答

4

你快到了,你需要的只是语法。

// SPECIAL CASE with vector of vectors 
template < typename element_type > 
class Container<std::vector<element_type>> 

你也可以从vector提取分配器类型,如果你真的想支持不同的分配器。

我不知道我是否走得太远与templateization

如果你写一个模板或不之间进行选择,通常你不应该。否则,这里什么都不是可疑的。

+0

它有效,但对我来说这似乎很神奇,因为我没有在原始/常规模板定义中定义'element_type'。 – Michael 2014-12-02 12:45:06