c++ 模板的含义如何理解,一段代码讲透彻。

#include <iostream>

#include<string>

using namespace std;

//#define putongfangfa

#define muban

#ifdef putongfangfa

void Print(int a )

{

    std::cout << a << std::endl;

}

void Print(string a )

{

    std::cout << a << std::endl;

}

void Print(float a )

{

    std::cout << a << std::endl;

}

int main()

{

    //如果想用类似Print()函数打印不同数据类型的数据,需要分别实现三个函数,

    //而这三个函数之间唯一的区别就是参数类型不同,如上面所示

    Print(5);

    Print("hello world");

    Print(5.5f);

    int b;

    std::cin >> b;

    return 0;

}

#endif

#ifdef muban

/*模板的使用情景一:在某些数据类型,尤其是函数参数类型不确定的情况下,可以使用此方法。

//三个函数,仅仅因为数据类型的不同,就需要写三个函数效率是比较低下的,这就是模板的意义之一。

template <typename T>  //template <class T> 将typename代替成class也可以。

void Print(T a)

{

    cout << a << endl;

}

void Print(int a )  //冲突的时候,优先选择非模板的函数。

{

    std::cout << 666 << std::endl;

}

int main()

{

   

    //第一种调用方法

    Print<int>(4);

    Print<string>("hello world2");

    Print<float>(5.6);

    //第二种调用方法

    Print(5);  

    Print("hello world");

    Print(5.5f);

   

    int b;

    std::cin >> b;

    return 0;

}

*/

//模板的使用情景二:在某些数组的应用中,数据类型不确定,数组大小不确定,可以使用此方法。

//数组大小不确定。

/*template<int N>

class array

{

    public:

        int arr[N];

        int getSize()

        {

            return N;

        }

};

int main()

{

    array<6> a;

    cout << a.getSize() << endl;

    int b = 0;

    cin >> b;

    return 0;

}*/

// 数组类型不确定,大小也不确定

template<typename T, int N>

class array

{

    public:

        T arr[N];

        int getSize()

        {

            return N;

        }

};

int main()

{

    array<int, 8> a;

    cout << a.getSize() << endl;

    for(int i = 0; i < a.getSize(); i++ )

    {

        cout << a.arr[i] << " ";

    }

    int b = 0;

    cin >> b;

    return 0;

}


 

#endif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值