我不确定模板化是否走得太远,但存在以下问题:
我有一个容器类。这个类可以直接取值,也可以取带值的向量。我想专门针对第二种情况。
我怎样才能...
代码示例:
// 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
}
};
Run Code Online (Sandbox Code Playgroud)
(当然,我的 Container 比这里显示的要复杂一些。我也可以创建两个不同的非模板版本的容器。但经过考虑,我也很好奇如何通过专业化来做到这一点。)
你快到了,你需要的只是语法。
// SPECIAL CASE with vector of vectors
template < typename element_type >
class Container<std::vector< element_type >>
Run Code Online (Sandbox Code Playgroud)
vector如果您确实想要支持不同的分配器,您还可以从 中提取分配器类型。
我不确定我是否在模板化方面走得太远
如果您可以选择是否编写模板,通常您不应该这样做。否则,这里没有什么可疑的。