- 需要注意的是,模板中函数或方法,要在类或头文件中实现。
- 关键字typename 和class基本等同。
- 构造类模板时,要指明模板参数类型,而函数模板则不用指明参数类型。
#pragma once
#include
#include
using namespace std;
template <typename T>
T compare(T t1, T t2) {
if (t1 > t2) {
return t1;
}
else {
return t2;
}
};
template <typename T>
class TEST {
public:
T m_t;
TEST() {};
virtual ~TEST() {};
T compare(T t1, T t2) {
return t1 > t2;
};
int comparestr(T t1 = string, T t2 = string) {
string s1 = t1;
string s2 = t2;
char * buf1 = (char*)s1.c_str();
char * buf2 = (char*)s2.c_str();
return (buf1[0]> buf2[0]);
};
};
- 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
#include
#include
#include
#include "main.h"
using namespace std;
int main() {
try {
double resd = 0;
int res = 0;
const char * resc = 0;
resd = compare(7.01, 7.1);
res = compare(6, 5);
resc = compare("hello", "world");
TEST<char*> test;
TEST<double> testd;
int result = 0;
double resultd = testd.compare(6.6789, 7.01);
resultd = testd.compare(6.6789, 6.7);
result = test.comparestr("testo","hello");
throw("hello world!\r\n");
}
catch (char * ex) {
try {
printf("throw string:%s\r\n", ex);
throw(12345678);
}
catch (int e) {
printf("throw number:%d\r\n", e);
}
}
return 0;
}
- 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