簡體   English   中英

使嵌套容器具有模板功能

[英]Make template function for nested container

我正在嘗試制作一個通用的測試函數,該函數接受諸如列表,集合或向量之類的容器,並返回嵌套的容器:列表列表,集合集,向量矢量。 非泛型函數如下所示:

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是另一種類型的容器(關聯),無論如何它可能都需要專用功能。

我認為您不能自動執行此操作,但是如果您指定類型,則可以設置模板功能:

template <typename T>
T test(typename T::value_type& in_container)
{
    T out_container;
    return out_container;
}

int main()
{
    vector<string> v;
    v.push_back("hello");
    auto w = test<vector<vector<string>>>(v); // w is a vector<vector<string>> now
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM