connection_status_t
in the top example is a type alias -- it's another name for the type bool
.
why could I not just do something like:
The second example you've given is not the same thing, because connection_status_t
is actually a variable in that code. So you could do that, but it means something different. If you omit bool connection_status_t;
then it would be a comparable example.
To get to the point of your question, type aliases are used to improve code readability by giving built-in types semantic meaning that humans understand. connection_status_t
tells me that the return value is going to indicate the status of the connection, just by looking at the code. bool
doesn't give me any clue about what the return value might indicate, it only informs me of the return value's domain.
Type aliases can also be used to ensure that the same type is used across a codebase where the actual type could be swapped out for a compatible type later. For example, one could have using id_set_t = std::set<std::string>;
and later change it to std::unordered_set<std::string>
. This only requires altering the type alias; everything that uses id_set_t
will suddenly start using the new type without having to hunt down all usages of that type.