簡體   English   中英

使用接口在C ++中一般采用容器的最佳方法是什么(即相當於在C#中將IEnumerable作為參數)

[英]What is the best way to take generically a container in C++ using interfaces (i.e. equivalent of taking IEnumerable as argument in C#)

我希望C ++構造函數/方法能夠將任何容器作為參數。 在C#中,使用IEnumerable會很容易,在C ++ / STL中是否有等價物?

安東尼

C ++的方法是使用迭代器。 就像所有<algorithm>函數一樣(it begin, it end, )作為前兩個參數。

template <class IT>
T foo(IT first, IT last)
{
    return std::accumulate(first, last, T());
}

如果您真的想將容器本身傳遞給函數,則必須使用“模板模板”參數。 這是因為C ++標准庫容器不僅使用所包含類型的類型進行模板化,而且還使用分配器類型進行模板化,該類型具有默認值,因此是隱式的且未知。

#include <vector>
#include <list>
#include <numeric>
#include <iostream>

template <class T, class A, template <class T, class A> class CONT>
T foo(CONT<T, A> &cont)
{
    return std::accumulate(cont.begin(), cont.end(), T());
}

int main()
{
    std::vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);

    std::list<int> l;
    l.push_back(1);
    l.push_back(2);
    l.push_back(3);

    std::cout << foo(v) << " " << foo(l) << "\n";

    return 0;
}

取決於你想要用容器做什么。 一想法:如果要訪問容器中存儲的內容,只需傳遞一個迭代器。

一個好問題,+ 1。 真可惜,它已經兩年了......無論如何我都會發布一個答案:如果你只是想公開你的圖書館的界面,你就會陷入“C ++方式”。 我這樣做的方法是:

template<class TValue>
class IEnumerator {
 public:
  virtual bool MoveNext() = 0;
  vírtual TValue Current() = 0;
  virtual void Reset() = 0;
};

template<class TValue>
class IEnumerable {
 public:
  virtual std::unique_ptr< IEnumerator<TValue> > GetEnumerator() const = 0;
};

這樣,您可以編寫以下類型的API:

void MyAPI(const IEnumerable<IMyLibAPIObject>& pSequence);

當然,我提供了不同的實現,如StlEnumeratorStlEnumerable ,或EnumeratorAdaptor<T, U>以獲得協方差,如在C#中...

干杯,

保羅

編輯:到目前為止,我最終得到了一個類型擦除'AnyEnumerator'和'AnyEnumerable'。 另外,我知道各種'any_iterator'實現......

暫無
暫無

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

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