c++ - 为嵌套容器制作模板函数

标签 c++ templates c++11

我正在尝试制作一个通用测试函数,它接受一个容器,例如列表、集合或 vector ,并返回嵌套容器:列表的列表、集合的集合、 vector 的 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;
}

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

最佳答案

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);
}

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

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

关于c++ - 为嵌套容器制作模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31174008/

相关文章:

templates - 使用 api 获取 wiki 页面的模板数据

c++ - 这不能用可变参数模板参数包来完成吗?

c++ - 强制局部变量默认初始化

c++ - 为什么 std::basic_string 不支持通过表达式模板进行连接?

c++ - 模板类是否在 C++ 的不同编译单元中编译了多次?

c++ - 这段代码是什么意思 "ofstream fout(getenv("OUTPUT_PATH"));"

c++ - 在 C++ 中初始化变量的 = 和 {} 语法之间的区别

c++ - Sieve of Eratosthenes 算法的效率

c++ - sigsegv 使用 vector STL

c++ - 具有多个模板参数的概念