I've noticed std::
containers tend to have public
, in-class type aliases (typedef
/using
).
E.g., see Member Types at http://en.cppreference.com/w/cpp/container/vector.
How are they useful? Aren't they just a relic of times when C++ didn't have things like auto
and decltype
?
When implementing a custom container, should it have such typedef
s? What do I lose if I fail to provide them?
If you restrict using the typedef ed name within your class, then make it private . It is certainly common practice to rename a type using typedef to a more usable/easily understandable name at the domain level.
typedef is necessary for many template metaprogramming tasks -- whenever a class is treated as a "compile-time type function", a typedef is used as a "compile-time type value" to obtain the resulting type.
Similarly, typedef can be used to define a structure, union, or C++ class.
The typedef keyword allows the programmer to create new names for types such as int or, more commonly in C++, templated types--it literally stands for "type definition". Typedefs can be used both to provide more clarity to your code and to make it easier to make changes to the underlying data types that you use.
If you want a standard-library-compatible container, you do have to supply the typedefs.
If you look at the documentation, e.g. at cppreference, you will see passages like this:
std::vector meets the requirements of Container, AllocatorAwareContainer, SequenceContainer, ContiguousContainer (for T other than bool) (since C++17) and ReversibleContainer.
If you look up Container or SequenceContainer or any other thing listed there, you will find a list of requirements, and the typedefs (or rather types—they don't have to be typedefs, though they often are) are among them.
So if you are building a Container in the standard sense of the term, you need to provide the typedefs (and of course satisfy all other requirements too).
C++11 could in theory loosen the requirements, but it didn't. Perhaps because
std::vector<int>::iterator
is a heck of a lot more readable than
decltype(std::declval<std::vector<int>>().begin())
Or perhaps for some other reason.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With