-
Notifications
You must be signed in to change notification settings - Fork 33
/
16.34.txt
24 lines (18 loc) · 1.09 KB
/
16.34.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
Exercise 16.34: Given only the following code, explain whether each of these
calls is legal. If so, what is the type of T? If not, why not?
template <class T> int compare(const T&, const T&);
(a) compare("hi", "world");
(b) compare("bye", "dad");
By Faisal Saadatmand
(a) Illegal: The parameter types are passed by reference (T&); thus, the
types are deduced as array's (const char[2] and const char[4]) rather than
decaying into pointers (const char*), and given that the template has only
one parameter (T), both argument must have the same type.(p. 680) Remember
that the size of an array is part of its type. Here, the size of "hi" is
smaller than "world", and therefore, their types do not match, making the
code illegal.
(b) Legal, both arguments have the same type (and size). See (a) for the
explanation.
For further (excellent) explanation on template argument deduction, refer
to Chapter 1 in Scott Meyer's Effective Modern C++:
Meyers, Scott. Effective Modern C++: 42 Specific Ways to Improve Your Use of C++11 and C++14. 1 edition. Beijing ; Sebastopol, CA: O’Reilly Media, 2014.