Is there a standard C++ equivalent of IEnumerable<T> in C#?

derekhh picture derekhh · Jan 6, 2012 · Viewed 17.8k times · Source

Or is it safe to use vector if the Enumerator of T is just listing all the elements?

Answer

Ben Voigt picture Ben Voigt · Jan 6, 2012

It isn't needed in C++, and here's why:

C# only supports dynamic polymorphism. So to create a reusable algorithm, you need an interface which all iterators will implement. That's IEnumerator<T>, and IEnumerable<T> is a factory for returning an iterator.

C++ templates, on the other hand, support duck typing. That means you don't need to constrain a generic type parameter by an interface in order to access members -- the compiler will look up members by name for each individual instantiation of the template.

C++ containers and iterators have implicit interfaces which is equivalent to .NET IEnumerable<T>, IEnumerator<T>, ICollection<T>, IList<T>, namely:

For containers:

  • iterator and const_iterator typedefs
  • begin() member function -- fills the need for IEnumerable<T>::GetEnumerator()
  • end() member function -- instead of IEnumerator<T>::MoveNext() return value

For forward iterators:

  • value_type typedef
  • operator++ -- instead of IEnumerator<T>::MoveNext()
  • operator* and operator-> -- instead of IEnumerator<T>::Current
  • reference return type from operator* -- instead of IList<T> indexer setter
  • operator== and operator!= -- no true equivalent in .NET, but with container's end() matches IEnumerator<T>::MoveNext() return value

For random access iterators:

  • operator+, operator-, operator[] -- instead of IList<T>

If you define these, then standard algorithms will work with your container and iterator. No interface is needed, no virtual functions are needed. Not using virtual functions makes C++ generic code faster than equivalent .NET code, sometimes much faster.


Note: when writing generic algorithms, it's best to use std::begin(container) and std::end(container) instead of the container member functions. That allows your algorithm to be used with raw arrays (which don't have member functions) in addition to the STL containers. Raw arrays and raw pointers satisfy all other requirements of containers and iterators, with this single exception.