c++ - Make template function for nested container -
i'm trying make generic test function takes container such list, set or vector, , returns nested container: list of lists, set of sets, vector of vectors. non-generic functions this:
vector<vector<string>> test(vector<string>& in_container) { vector<vector<string>> out_continer; // out_continer filed using values in_container return out_continer; } list<list<int>> test(list<int>& in_container) { list<list<int>> out_continer; // out_continer filed using values in_container return out_continer; } set<set<float>> test(set<float>& in_container) { set<set<float>> out_continer; // out_continer filed using values in_container return out_continer; }
but dont know how make 1 template test function equivalent these separate test examples.
vector
, list
(and deque
) have identical sets of template parameters , ordinary sequences, can cover them with
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 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); }
(the code bit convoluted since have specify allocator type outer container explicitly, can improved.)
meanwhile set
different kind of container (associative), require dedicated function anyway.
Comments
Post a Comment