Jason C
Jason C

Reputation: 40336

Unit testing custom STL-compatible containers and iterators

I've just implemented a custom iterator type for a custom container. The container models the C++17 ReversibleContainer, and its iterators (both const and non-const) model LegacyRandomAccessIterator.

My question is; is there some sort of built-in thing in std that I can use to test if both the container and its iterators adhere to the specified named requirements, or do I have to write all the tests myself (which is mostly doable for me but I'd rather not reinvent the wheel; and also I'm not sure I'm enough of a template wizard to really thoroughly prove that e.g. types and such are correct)?

Things like (I know this is one of many), e.g. this from the operational semantics of operator <:

custom_container::iterator a = ...;
custom_container::iterator b = ...;
assert((a < b) == (b - a > 0));

And that return types are correct, etc., and such.


I've managed to find some capabilities already, for example <type_traits> has some useful utilities like:

if (!std::is_copy_constructible<custom_container::iterator>::value)
   /* fail test */ ;

Which is good for some of the fundamental named requirements at least.

Upvotes: 1

Views: 227

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275480

No there us not.

In fact proving a type satisfies all requirements of being an iterator cannot be done statically in C++.

You can test statically if the types are correct, and that operators and the like exist. But ths semantics cannot be proven in the general case (I think both practically and theoretically due to Rice's theorem).

I find most of the requirements are easy to check in practice (if not as easy to automate). The most common gotcha I find is that "legacy" iterators stronger than input iterators must have actual backing persistent data they return references and pointers to; that data cannot live within the iterator, or be otherwise temporary/generated.

Upvotes: 3

Related Questions