So I am looking through this handout that describes the code for std::pair
. Below is the code:
template <class U, class V>
struct pair {
U first;
V second;
pair(const U& first = U(), const V& second = V()) :
first(first), second(second) {}
};
template <class U, class Y>
pair<U, V> make_pair(const U& first, const V& second);
I am trying to understand this code but I am having problems, specifically at the line pair in the struct. I understand that we store two create two variables first and second according to the respective classes.
In the argument of the pair function, I see that we create a new class U
and V
and assign them respectively to first
and second
, but I don't clearly understand how the const U&
works because of the ampersand sign. What's more confusing is the use of a colon after the function declaration which I have never seen before used in c++.
I also don't understand the line below declaring first(first)
and second(second)
especially with the brackets. Isn't first
a type, so how are we able to call a function from first
?
We'll address this by dividing it into parts.
U&
means that we are passing a variable of type U
that will be used by reference - the variable used by the constructor is the same one (same memory address and value) that is given as an argument. By saying const U& first = U()
we are saying that we promise not to change the first
passed into the constructor ( const ...
), we want first
to be taken by reference ( ...U&...
), and if we don't provide first
in the constructor we should use a U
provided by U
's default constructor ( ... = U()
). For more information on references, this page should help.
first(first)
is part of a "constructor initialization list" - the preferred method for initializing class member variables in a constructor. We tell the constructor that we are initializing the member variable of pair
called first
( first(...)
) with the argument first
provided by the constructor (the U&
we discussed earlier). For more information on constructor initialization lists, this page should help.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.