forked from pezy/CppPrimer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
53 lines (45 loc) · 1.66 KB
/
main.cpp
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
47
48
49
50
51
52
53
/***************************************************************************
* @file main.cpp
* @author Alan.W
* @date 07 Feb 2014
* @remark This code is for the exercises from C++ Primer 5th Edition
* @note
***************************************************************************/
//!
//! Exercise 16.37:
//! The library max function has two function parameters and returns the
//! larger of its arguments. This function has one template type parameter.
//! Could you call max passing it an int and a double? If so, how? If not,
//! why not?
// If so, it doesn't compile, because the two argument must be the same type or
// convertible.
//
//! Exercise 16.38:
//! When we call make_shared (§ 12.1.1, p. 451), we have to provide an
//! explicit template argument. Explain why that argument is needed and
//! how it is used.
//!
// without specified type given, make_shared has no possibility to
// to determine how big the size it should allocate, which is the reason.
//
// Depending on the type specified, make_shared allocates proper size of memory
// space and returns a proper type of shared_ptr pointing to it.
//!
//! Exercise 16.39:
//! Use an explicit template argument to make it sensible to pass two string
//! literals to the original version of compare from § 16.1.1 (p. 652).
//!
#include <iostream>
template <typename T>
int compare(const T &v1, const T &v2)
{
if (v1 < v2) return -1;
if (v2 < v1) return 1;
return 0;
}
int main()
{
std::cout << compare<std::string>("sss","aaa") << "\n";
//! ^^^^^^^^^^^^^
//! There is a normal conversion here, since it's an explicit argument.
}