C++模板 基础(一)

    技术2022-05-20  27

    C++模板 基础(一)

    为什么使用Templates?

    使代码更高效,减少重复劳动

     

     

    一.function templates

     

    function templates可以为不同类型的问题提供解决方法,一个function template可以表示一族function。其作用跟function是一样的,只是function templates没有被参数化,所以用途很广泛

     

    //file: max.hpp

     

    example:

    template <typename T>

    inline T const & max(T const& a,T const& b)

    {

             return a < b ? b : a ;

    }

     

    this template represents a gens functions, the same effect that returns the bigger one .

    in this example, the keyword "typename"  is the same to the "class" , they have the same effect. however, it is not the "struct"

    这个例子表示一族函数,其作用就是返回二个数中的大数,在上面模板类中,typename可以与class互换,但是typename与struct是不同的。

     

    //file: max.cpp

     

    the example of calling the template

    #include<iostream>

    #include<string>

    #include "max.hpp"

     

    using namespace std

     

    int main()

    {

            int i = 42;

            cout<<"max(7,i):  "<<max(7,i)<<endl;

     

            double f1 = 3.4;

            double f2 = -4.5;

            cout<<"max(f1,f2):  "<<max(f1,f2)<<endl;

     

            char *s1 = "computer graphics";

            char *s2 = "graphics";

            cout<<"max(s1,s2):  "<<max(s1,s2)<<endl;

     

            return 0;

    }

     

    程序运行结果为:

    max(7,i):  42

    max(f1,f2): 3.4

    max(s1,s2):  computergraphics

     

    代码中调用了三次max(),每次传进去的参数类型都不同。

     

    一般而言,template不会被编译为处理任意类型的实体,而是被编译为多个个别实体,每一个处理某一种特定的类型,比如这个就是三个不同的类型,都是对template parameter具体化了。不用程序员自己去写很多不同类型参数的函数,所以这就为程序员节约了很大的劳动力(对于大项目而言) 。

     

    实际上,template会被编译2次

    1.没有具体化,检查语法错误

    2.具体化,检查代码中的参数是否合法

    这里需要注意的问题,在以后会详细说

     

     

    二.参数传递

    template是不允许自动转换参数类型的,每个T必须跟定义的完全匹配

    比如 max(2,4.5) 会出错

    解决方法:如下二种

    max(<double>(2),4.5)

    max<double>(2,4.5)

     

     

    后面的内容待续。。。。

    如觉得上面内容有问题,欢迎一起讨论,谢谢


    最新回复(0)