天天看点

C++模版template用法

template用法

C++和python区别:

  • C++是

    强类型语言

    ,python是

    弱类型语言

  • 区别在于,python可以

    把任意类型的变量传入处理

    ,而C++需要

    声明不同的变量类型

  • 这就导致了,若编写一个比大小的函数,C++要写int/float/char等等的多种,很麻烦;
  • 因此出现了template模版的定义;

如下列实现了一个不区分int/float/…比较大小的函数

template<typename T>
int compare(T a, T b) {
    return a>b;
}

compare(15,16); // 这种不申明类型的写法也是允许的
compare<int>(1, 2); 
compare<float>(1.0, 2.0);
compare<char>('a','b');