-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcppTemplate.cpp
90 lines (82 loc) · 2.28 KB
/
cppTemplate.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <iostream>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <cstdio>
#include <cstdint>
class CFX {
public:
void display(void) {
std::cout << "\t\tFunction name: <" << __func__ << ">" << std::endl;
}
};
// function template
template <typename DataType>
void swap (DataType& a, DataType& b) {
DataType tmp = a;
a = b;
b = tmp;
}
template <typename DataType>
int compare(const DataType &v1, const DataType &v2)
{
if (v1 < v2) return -1;
if (v1 > v2) return 1;
return 0;
}
void simpleFunc(void) {
int i=2, j=3;
std::cout << "\tsimpleFunc: before i= " << i << " j= " << j << std::endl;
swap(i,j);
std::cout << "\tsimpleFunc: after i= " << i << " j= " << j << std::endl;
return;
}
// multiple arguments
template <typename T>
T add(T value) {
return value;
}
template <typename T, typename... Args>
T add(T first, Args... rest) {
return first + add(rest...);
}
void multipleArgs(void) {
std::cout << "\tmultipleArgs: add(1, 2, 3, 4, 5): " << add(1, 2, 3, 4, 5) << std::endl; // 输出:15
std::cout << "\tmultipleArgs: add(1.1, 2.2, 3.3): " << add(1.1, 2.2, 3.3) << std::endl; // 输出:6.6
}
// class template
template <typename T> class CTBlob {
public:
CTBlob() {}
CTBlob(T age):mAge(age) {}
~CTBlob(){}
T getAge() { return (mAge); }
T compareD(const T &v1, const T &v2) {
if (v1 < v2) return (T)-1;
if (v1 > v2) return (T)1;
return (T)0;
}
private:
T mAge;
};
void class_template(void)
{
std::cout << "\tclass_template enter" << std::endl;
CTBlob <int> ctBlob(20); //用int实例化
std::cout << "\t\tctBlob(20).age= "<<ctBlob.getAge()<< std::endl;
}
//end
template <typename T>
typename std::enable_if<std::is_integral<T>::value, T>::type
onlyForIntegers(T value) {
return value * 2;
}
int main() {
std::cout << "main: enter" << std::endl;
//simpleFunc();
multipleArgs();
class_template();
std::cout << "\t onlyForIntegers: 2 = " << onlyForIntegers(1) << std::endl; // 输出:15
std::cout << "main: exit" << std::endl;
return 0;
}