C++ template

本文介绍了C++中的函数模板和类模板的应用,展示了如何使用模板来简化代码并提高复用性,通过实例说明了模板的基本语法及其实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景

在解析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函数中声明或定义一个模板。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值