背景
在解析protobuffer时,要先把字符串unescape,然后去掉首尾空格,再用proto的接口去解析,把这一系列操作封装成一个函数。之前,不同的proto我封装成了不同的函数,很多都是可以复用的操作,所以用template
函数模板
举个栗子:
#include <string>
#include <iostream>
void PrintNumber(const int& num)
{
std::cout << num << std::endl;
}
void PrintDouble(const double& num)
{
std::cout << num << std::endl;
}
int main()
{
int a = 3;
PrintNumber(a); // 输出3
double b = 3.0;
PrintDouble(b); // 输出3.0
return 0;
}
我想输出任意类型的数该怎么办呢?
#include <string>
#include <iostream>
using namespace std;
template<typename T> void PrintNumber(const T& var)
{
cout << var << endl;
}
int main()
{
int a = 3;
double b = 3.0;
PrintNumber(a);
PrintNumber(b);
return 0;
}
这样一个函数就搞定了!
类模板
#include <iostream>
template<class T1, class T2>
class Test {
public:
T1 t1;
T2 t2;
public:
Test(T1, T2);
T1 GetT1() {
return t1;
}
T2 GetT2() {
return t2;
}
void SetT1(T1 t) {
t1 = t;
}
void SetT2(T2 t) {
t2 = t;
}
T1 AddT1(T1 t);
static void PrintStatic() {
std::cout << "static" << std::endl;
}
};
template<class T1, class T2> Test<T1, T2>::Test(T1 t_1, T2 t_2) {
t1 = t_1;
t2 = t_2;
}
template<class T1, class T2> T1 Test<T1, T2>::AddT1(T1 t) {
t1 += t;
return t1;
}
int main() {
Test<int, double> test(0, 0.0);
test.SetT1(1);
test.SetT2(1.0);
std::cout << test.GetT1() << std::endl;
std::cout << test.GetT2() << std::endl;
std::cout << test.AddT1(2) << std::endl;
std::cout << test.GetT1() << std::endl;
Test<int, double>::PrintStatic();
return 0;
}
另外:模板的声明或定义只能在全局,命名空间或类范围内进行。即不能在局部范围,函数内进行,比如不能在main函数中声明或定义一个模板。