Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are public, in-class typedefs necessary in C++1y?

Tags:

c++

c++11

c++14

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 typedefs? What do I lose if I fail to provide them?

like image 728
PSkocik Avatar asked Jan 24 '16 12:01

PSkocik


People also ask

Can typedef be private?

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.

Is typedef necessary in C++?

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.

Can you typedef in a class C++?

Similarly, typedef can be used to define a structure, union, or C++ class.

Why should I use typedef?

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.


1 Answers

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.

like image 141
n. 1.8e9-where's-my-share m. Avatar answered Oct 06 '22 00:10

n. 1.8e9-where's-my-share m.