函数模板->模板函数

#include <iostream>
#include <string>
using namespace std;

/**
 * 定义模板函数exchange
 * 实现功能:交换两个数的位置
 * -------------------------------------
 * 定义函数模板的时候确定需要几个变量,几个常量.
 * 变量由 typename 或者 class 声明,但没有指明类型
 * 常量声明的时候必须确定类型,在编译的时候被看做常量处理.
 * 在使用模板函数的时候,必须依次指明需要的数据类型,用 "< >" 括起来, 常量也必须明确指明所对应的类型的一个值.
 * 调用模板函数的时候, < > 中的类型内容,与声明函数模板的时候相同,如:
 * template<class C, int Ksize>
 * display<string, 5>("hello world.");
 */
template<typename T>
void exchange(T a, T b)
{
    T temp = a;
    a = b;
    b = temp;
}
template<typename T, typename S>
void display(T t, S s)
{
    cout << t << endl;
    cout << s << endl;
}

template<class C, int Ksize>
void display(C Str)
{
    for (int i=0; i<Ksize; ++i)
    {
        cout << Str << endl;
    }
}
int main(void)
{
    int x = 10;
    int y = 20;
    // 调用模板函数
    exchange<int>(x,y);
    cout << "x = " << x << endl;
    cout << "y = " << y << endl;

    display<char, double>('h', 3.14);
    display<string, 5>("hello world."); //打印5行string类型的"hello world."
    
    return 0;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容