-
Notifications
You must be signed in to change notification settings - Fork 33
/
18.18.txt
46 lines (35 loc) · 1.94 KB
/
18.18.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
Exercise 18.18: Given the following typical definition of swap § 13.3 (p. 517),
determine which version of swap is used if mem1 is a string. What if mem1 is an
int? Explain how name lookup works in both cases.
void swap(T v1, T v2)
{
using std::swap;
swap(v1.mem1, v2.mem1);
// swap remaining members of type T
}
By Faisal Saadatmand
Inside the user defined swap(T v1, T v2) function, the using declaration
using std::swap;
will make the version of the swap (and its overloads) in the standard library
visible without qualifications in the local scope. (p. 793) Thus, the call swap:
swap(v1.mem1, v2.mem1);
will use the names from the injected namespace by the using declaration in its
normal name look-up procedure. The look-up will search 'upwards' through the
enclosing scope. (p. 796-797)
If mem1 were a string (a class object), however, in addition to the normal name
look-up, the compiler will perform an argument-dependent lookup. That is, "it
will search the namespace in which the argument's class is defined in addition
to the normal scope lookup." (p. 798)
In this case, the search will start in the current scope, which will find a
viable function in the std namespace. Then it moves outwards to the enclosing
scope (the global scope) and finds another viable function, which is the user
defined swap. Finally, it will search the string class namespace and finds yet
a third viable swap functions. Given that all three functions are templates
with the same number of parameters, they are equally good matches. Thus, the
call is ambiguous.
If mem1 were an int, the compiler will perform normal name look-up. In the
current scope and it will match an std version of swap.
It is worth noting that an argument-dependent look-up is performed when we pass
a class object to void swap(T v1, T v2), which is the case with our example.
This means that the initial (from main or other functions) call to swap will be
subject to argument dependent look-up.