为嵌套容器创建模板功能

bat*_*est 1 c++ templates c++11

我正在尝试创建一个通用测试函数,它接受一个容器,如list,set或vector,并返回嵌套容器:列表列表,集合集合,向量向量.非泛型函数如下所示:

vector<vector<string>> test(vector<string>& in_container)
{
    vector<vector<string>> out_continer;

    // out_continer will be filed using values from in_container

    return out_continer;
}

list<list<int>> test(list<int>& in_container)
{
    list<list<int>> out_continer;

    // out_continer will be filed using values from in_container

    return out_continer;
}

set<set<float>> test(set<float>& in_container)
{
    set<set<float>> out_continer;

    // out_continer will be filed using values from in_container

    return out_continer;
}
Run Code Online (Sandbox Code Playgroud)

但我不知道如何制作一个与这些单独的测试示例等效的模板测试功能.

AnT*_*AnT 5

vectorlist(和deque)具有相同的模板参数集,并且是普通序列,因此您可以使用它们来覆盖它们

template <typename T, typename U, template <typename, typename> class C>  
C<C<T, U>, std::allocator<C<T, U>>> test(C<T, U> &in)
{
  C<C<T, U>, std::allocator<C<T, U>>> out;
  // Fill it here
  return out;
}

int main() 
{
  std::vector<int> v;
  std::vector<std::vector<int>> vv = test(v);

  std::list<int> l;
  std::list<std::list<int>> ll = test(l);
}
Run Code Online (Sandbox Code Playgroud)

(代码有点复杂,因为我们必须明确指定外部容器的分配器类型,但它可能会得到改进.)

同时set是一种不同类型的容器(关联),无论如何都可能需要专用功能.