0

I am fairly new to C++ and am trying to understand the functionality of the keyword "using". I just don't understand when and why it is supposed to be used.

For example, I have this code:

using connection_status_t = bool;

connection_status_t isFileOpenForInput(ifstream& ifs, const string& filename) {
    ifs.open(filename);
    return ifs.is_open();
}

For this specific example, why could I not just do something like:

bool connection_status_t;

bool isFileOpenForInput(ifstream& ifs, const string& filename) {
    ifs.open(filename);
    return ifs.is_open();
}
capnconn
  • 5
  • 2

2 Answers2

1

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.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
0

You can just use is the normal way.

Using would be advisable, if you want to switch the type later on. In your example, you may later want to switch bool with an enum:

enum connection_status_t
{
failed = 0,
success = 1,
no_result = 2
}

To put it simple: using is a kind of alias system. You can use it as well for classes/types/structs etc. that are in namespaces to abbreviate something:

using ::namespace::class

This way, you don't have to write the whole namespaces.

SAlex
  • 361
  • 2
  • 10