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

后端 未结 4 727
有刺的猬
有刺的猬 2020-12-04 16:44

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

4条回答
  •  时光取名叫无心
    2020-12-04 17:20

    If we stick to the question strictly the answer is no, as far as I know. People have kept replying what is the substitute available in C++, which may be good info but not answers, and which the OP most probably knew already.

    I completely disagree that "it is not needed," it is just that the designs of the C++ and .NET standard libraries are different. The main feature of IEnumerable<> is that it's polymorphic, and so it enables the caller to use whatever class he wants (array, List, Set etc.), while still providing compile-time strong typing, fail-safe even in library APIs.

    The only alternative in C++ is templates. But C++ templates are not safely typed run-time generics, they are basically kind of macros. So first of all with templates in C++ you are forced to provide the whole template source code to whoever needs to use your template. Moreover if you make your library API templated you lose the ability to guarantee that a call to it will compile, and the code is not automatically self-documenting.

    I fully sympathize with any other programmer who uses both C# and C++ and is frustrated with this point.

    However C++2X is planned to add features including ranges (which may satisfy the OP?); as well as concepts (which address the weak/bad type-checking of templates -- flaw admitted by Bjarne Stroustrup himself), and modules (which may or may not help reducing the pain from header-only templates).

提交回复
热议问题